Recipe 4.20. Using printf in PythonCredit: Tobias Klausmann, Andrea Cavalcanti ProblemYou'd like to output something to your program's standard output with C's function printf, but Python doesn't have that function. SolutionIt's easy to code a printf function in Python: import sys def printf(format, *args): sys.stdout.write(format % args) DiscussionPython 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 AlsoLibrary 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. |