Archive
Posts Tagged ‘print_r’
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")
