Recipe 4.20. Using printf in Python
Credit: Tobias Klausmann, Andrea Cavalcanti
Problem
You'd like to output
something to your program's standard output with
C's function printf, but Python
doesn't have that function.
Solution
It's easy to code a printf
function in Python:
import sys
def printf(format, *args):
sys.stdout.write(format % args)
Discussion
Python separates the concepts of output (the print
statement) and formatting (the % operator), but if
you prefer to have these concepts together, they're
easy to join, as this recipe shows. No more worries about automatic
insertion of spaces or newlines, either. Now you need worry only
about correctly matching format and arguments!For example, instead of something like:
print 'Result tuple is: %r' % (result_tuple,),with its finicky need for commas in unobvious places (i.e., one to
make a singleton tuple around
result_tuple, one to avoid the newline
that print would otherwise insert by default),
once you have defined this recipe's
printf function, you can just write:
printf('Result tuple is: %r', result_tuple)
See Also
Library Reference and Python in a
Nutshell documentation for module sys
and for the string formatting operator %; Recipe 2.13 for a way to implement
C++'s <<-style output in
Python.