Home > python > Print in Python 2

Print in Python 2

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

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


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: , , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: