• Skip to main content
  • Skip to primary sidebar

CodeBlogMoney

Make Money using Coding and Blogging

python

XML Pretty Print using Python – with Examples

May 30, 2018 by Jimmy

XML Pretty Print using Python is required frequently for testing, analyzing and debugging XML data. Python and XML both are treading in programming fields. Python generates dynamic XML string and received by the client. To save memory or bandwidth it’s better to send the minified version of XML text.

Some time for debugging purposes, we need to see beautified XML data to understand and to Debug. This article will help to pretty-print XML data.

There are two examples in the post.

  1. Pretty Print XML String
  2. Pretty Print XML File

1. XML Pretty Print using Python

Here is an example:

import xml.dom.minidom

uglyxml = '<?xml version="1.0" encoding="UTF-8" ?><employees><employee><Name>Leonardo DiCaprio</Name></employee></employees>'

xml = xml.dom.minidom.parseString(uglyxml)

xml_pretty_str = xml.toprettyxml()

print xml_pretty_str

Result :

<?xml version="1.0" ?>
<employees>
  <employee>
    <Name>Leonardo DiCaprio</Name>
  </employee>
</employees>

Here is the explanation for the code.

  1. import xml.dom.minidom

This is an XML library available in python to convert the DOM object from XML string or from the XML file.

  1. xml.dom.minidom.parseString

parseString is a method which converts XML string to objectxml.dom.minidom.Document.

  1. xml.toprettyxml

toprettyxml This method will indent the XML data and return as Pretty XML string.

2. XML Print Print from File using Python

Here is the Example:

import xml.dom.minidom

with open('xmlfile.xml') as xmldata:
    xml = xml.dom.minidom.parseString(xmldata.read())  # or xml.dom.minidom.parseString(xml_string)
    xml_pretty_str = xml.toprettyxml()

print xml_pretty_str

This program reads from file and load and create XML Document objects and print the XML data in beautiful XML String.

I have used these tools for creating this blog post.

XML Formatter

XML Viewer

Related articles:

JSON Pretty Print using Python

Filed Under: Python, XML Tagged With: pretty print, python, XML

Read JSON File using Python Code and Prompt

May 30, 2018 by Jimmy

Read JSON File using Python requires importing the JSON library of Python. Before we deep dive in code let me brief you about the JSON.

JSON (Javascript Object Notation) is easy to read, write, analyze and flexible string-based format which can be used to serialized (store) and transfer between multiple application, products and between the multiple layers (Client/Server).

I have been playing around with JSON from the last 5 years in Python, Javascript, NodeJS, and JAVA.

Program to Read JSON file using Python:

import json

with open('jsonfile.txt') as jsonfile:
    parsed = json.load(jsonfile)

print json.dumps(parsed, indent=2, sort_keys=True)

Create a jsonfile.txt using this JSON data. a parsed variable will become a dictionary object out of parsing JSON file. Please check in the image, how the parsed object looks like in debug mode. to understand more about “json.dump”, please visit JSON Pretty Print using Python.

Read JSON File using Python
JSON Object in Python IDE Debug
{
  "employees": {
    "employee": [
      {
        "id": "1",
        "firstName": "Tom",
        "lastName": "Cruise"
      },
      {
        "id": "2",
        "firstName": "Maria",
        "lastName": "Sharapova"
      },
      {
        "id": "3",
        "firstName": "James",
        "lastName": "Bond"
      }
    ]
  }
}

Read a Python File on Python Prompt.

>>> import json
>>> jsondata = json.loads(open('jsonfile.txt').read())
>>> jsondata
{u'employees': {u'employee': [{u'lastName': u'Cruise', u'id': u'1', u'firstName': u'Tom'}, {u'lastName': u'Sharapova', u'id': u'2', u'firstName': u'Maria'}, {u'lastName': u'Bon
d', u'id': u'3', u'firstName': u'James'}]}}

If you don’t have python setup and still want to open a JSON file to read. Please visit https://jsonformatter.org and click on an open file, select file from your system and it will open in JSON Editor.

I hope this article will help to read a JSON File using Python. Please share your views on this article.

Filed Under: JSON, Python Tagged With: File, json, python

Generate Random Number using Python

May 26, 2018 by Jimmy

Need some random numbers in your program? This article will help you to know different techniques to generate a random number in python. While developing small, large or enterprise applications, It requires generating random numbers. Let’s deep dive to Generate Random number using Python.

Python provides a ” random ” library to generate a random number using built un methods. Just “import random” and start generating a number which will be random.

Here is the example to generate a random integer number.

Generate Random number using Python

Using randint(a,b)

# Program to print 5 random integer numbers between 1 to 10000
import random
for x in range(5):
    print random.randint(1, 10000)

This program prints 5 random integer numbers between 1 to 10000. randint is an inbuilt function in python random library. It has two parameters.randint(a,b) It generates the random integer number N such that.a <= N <= b

Using random()

# Program to print 5 random numbers between 0.0 to 1.0
for x in range(5):
    print random.random()

This random function returns the random floating-point number in the range (0.0, 1.0).

For more information to generate random numbers, please visit the official python document for random.

https://docs.python.org/3/library/random.html

To learn more about Python, Please visit the Python category.

 

Filed Under: Python Tagged With: python, random number

JSON Pretty Print using Python- with Examples

May 25, 2018 by Jimmy

JSON Pretty Print using Python is required frequently for testing, analyzing and debugging JSON data. Python and JSON both are treading in programming fields. Python generates dynamic JSON string and received by the client. To save memory or bandwidth it’s better to send the minified version of JSON text.

Some time for debugging purpose, we need to see beautified JSON data to understand and to Debug. This article will help to pretty print JSON data.

There are two examples in the post.

  1. Pretty Print JSON String
  2. Pretty Print JSON File

1. JSON Pretty Print using Python

Here is an Example:

import json

uglyjson = '{"firstnam":"James","surname":"Bond","mobile":["007-700-007","001-007-007-0007"]}'

#json.load method converts JSON string to Python Object
parsed = json.loads(uglyjson)

print json.dumps(parsed, indent=2, sort_keys=True)

Result :

{
  "firstnam": "James", 
  "mobile": [
    "007-700-007", 
    "001-007-007-0007"
  ], 
  "surname": "Bond"
}

Here is the explanation for the code.

  1. import json

This is a JSON library available in python to convert Python object from JSON string or from JSON file.

  1. json.load

json.load is a method which converts JSON string to Python object. Here is the conversion table form JSON data type to Python data types.

JSON Python
object dict
array list
string unicode
number (int) int,long
number (real) float
true True
false False
null None
  1. json.dumps

json.dums is the opposite of json.load. It creates a JSON string from Python object. It takes parameters indent parameter which formats the JSON string.

2. JSON Print Print from File using Python

Here is the Example:

import json

with open('jsonfile.txt') as jsonfile:
    parsed = json.load(jsonfile)

print json.dumps(parsed, indent=2, sort_keys=True)

This program reads from file and load and create Python objects and dumps the JSON data in beautiful JSON String. Read JSON File using Python for more details

I have used these tools for creating this blog post.

JSON Editor

JSON Viewer

 

Filed Under: JSON, Python Tagged With: json, pretty print, python

Reverse String in Python – Best Approach Given

December 9, 2016 by Jimmy

There are many ways to reverse string in Python. If you are familiar with c , c++ and java and don’t want to use any reverse function then someone could write the logic like:

1. Using the swapping last char with first and do that until the middle character. Remember we used to do this kind of exercise in C, 101?

2. Second would be like to take a new string and add 1 by 1 character from the opposite order of the String. This may take up too much space if you have Essay to reverse.

Note: String is immutable in Python similar to in Java. So it will not change the string if you try to modify, it will create the new String.

Firstly I have not seen a use case where I need to reverse a string unless you are trying to work on Cryptography.

This is enough talking.

Let’s do the reverse string with Python.

Reverse String in Python – Best Approach

This is the best and effective way to reverse a string.

string_sample = "Hello World"

reversed_string  = string_sample[::-1]

print(reversed_string)

This is the very astonished result by writing [::-1] it reverse the String and this is the fastest way to reverse a string.

This is called extended slice syntax. It works by writing [begin:end:step] – (minus sign) by leaving begin and end off and by writing a step of -1 , this will reverse a string.

Here are some other ways to reverse a string in python.

Reverse a String using the recursive function.

def reverse(string):
    if len(string) <= 1:
        return string

    return reverse(string[1:]) + string[0]

string_sample = "Hello World"

print(reverse(string_sample))

Reverse a String by using Extra String Variable

Reverse a string by using another string variable and adding character one by one in the opposite of the given string.

def reverse(string):
    new_string = ''
    index = len(string)
    while index:
        index -= 1
        new_string += string[index]
    return new_string

string_sample = "Hello World"
print(reverse(string_sample))

This approach may hurt the performance of the application based on the string length.

So the best approach is to use  [::-1] and fastest.

Filed Under: Python Tagged With: python, Reverse, String

  • Go to page 1
  • Go to page 2
  • Go to Next Page »

Primary Sidebar

Categories

  • Blogging
  • HTML
  • Java
  • JavaScript
  • jQuery
  • JSON
  • MySql
  • Performance
  • PHP
  • Problem Solving
  • Python
  • Testing
  • XML

Copyright © 2021 · Metro Pro on Genesis Framework · WordPress · Log in