Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

4. Python Shortcuts > 4.20. Using printf in Python

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!


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint