Xah Lee, 2005-01-20
There are several ways to format output
strings. repr() is for turning a data into a
string form that can be read back into
Python. str() is focused on human readable
form.
# Python s = 3.14159 print str(s) print repr(s) # the repr() function has some methods for formatting for x in range(1,5): print repr(x).rjust(2), repr(x*x).rjust(3)
The “print” function itself supports string formatting in the style of C's printf.
#-*- coding: utf-8 -*- # python # the “print” support C's printf style of formatting print '%2d %6d %2.4f %s' % (1234, 5678, 3.1415926, 'Oh, dear!')
To print without the automatic line ending, use sys.stdout.write. Example:
# python import sys sys.stdout.write("something in the water") sys.stdout.write(" does not compute")
In perl, if you want to print arrays or hashes for later reading into perl program, you'll need to use Data::Dumper module.
For formatting strings, you can use “printf” and “sprintf”.
blog comments powered by Disqus