Main Content

Python printf

Archive - Originally posted on "The Horse's Mouth" - 2005-11-15 23:13:47 - Graham Ellis

To format data into a string in python, use the % operator as python doesn't have an sprintf or printf function. So why have I entitled today's entry "python printf? Because this in one of the most frequently asked, and infrequently answered questions.

The % operator with a string to its left formats the value to the right using the (sprintf style) string to to the left of the operator. Where you want to format more that one value, use a tuple to the right.

Here's an example in which I've formatted an integer to return a three digit number padded with leading zeros:

>>> licensed = 7
>>> callin = "Agent %03d" % licensed
>>> print callin
Agent 007
>>>


We've got an example using a tuple in our course material and there's an example using a format string variable and aligning output columns in python there too. There is further documentation of pythons' % operator on the Python documentation site (well hidden, so I give you the link!)

Aside - why no printf in python? Because you don't need it and the alternative is neater and better. Arguably, there shouldn't be a printf function in any other language either, as it both formats the values AND sends them to the output channel - doing two logical operations in a single call, and you're bound to want to separate them at some stage. Instead, there should be two functions. There usually are ... and from a purist's viewpoint, sprintf followed by echo or print is much more maintainable that a single sprintf.


Illustration - delegates on a Python Programming training course at Well House Manor - our residential training centre.