Archive

Posts Tagged ‘pprint’

catch the output of pprint in a string

December 29, 2014 Leave a comment

Problem
If you have a large nested data structure (e.g. a list or dictionary), the pprint module is very useful to nicely format the output.

However, “pprint.pprint” prints directly to the stdout. What if you want to store the nicely formatted output in a string?

Solution
Use “pprint.pformat” instead.

Example:

>>> import pprint
>>> d = {"one": 1, "two": 2}
>>> pprint.pprint(d)
{'one': 1, 'two': 2}
>>> s = pprint.pformat(d)
>>> s
"{'one': 1, 'two': 2}"

Well, this is a small example, the real pretty formatting is not visible, but you get the point :)

Categories: python Tags:

Print in Python 2

October 1, 2010 Leave a comment

Let’s see some examples how to print to the standard output:

#!/usr/bin/env python

import sys

a = "Alice"
b = "Bob"

print a     # "Alice\n", i.e. newline added
print b     # "Bob\n"

print a, b  # "Alice Bob\n", i.e. space is used as separator

print a + b # "AliceBob\n", i.e. the two strings are concatenated

for i in range(10):
    print i,    # "0 1 2 3 4 5 6 7 8 9", i.e. no newline, but space is still added
                # notice the comma after i

print       # "\n"

age = 7.5
print "Alice is " + str(age) + " years old."    # must use str() for converting
                                                # the float to string

print "%s is %.1f years old" % (a, age)         # like C's printf()
    
for i in range(10):
    sys.stdout.write(str(i))    # "0123456789", now you have full control
  
print

Using the pprint module, you can “pretty print” any data structure. It’s similar to PHP’s print_r function.

import pprint
pp = pprint.PrettyPrinter(indent=4)

li = []   # some complicated structure

pp.pprint(li)

How to print to the standard error? Easy:

#!/usr/bin/env python

import sys

sys.stderr.write("Reactor meltdown! Leave the building immediately!\n")
Categories: python Tags: , , , ,
Design a site like this with WordPress.com
Get started