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.
(written 2005-11-15 23:13:47)
Associated topics are indexed under
Y108 - Python - String Handling [2405] But I am reading from a file - no need to prompt (Perl) - (2009-09-14)
[2284] Strings as collections in Python - (2009-07-12)
[1876] Python Regular Expressions - (2008-11-08)
[1608] Underlining in Perl and Python - the x and * operator in use - (2008-04-12)
[1517] Python - formatting objects - (2008-01-24)
[1195] Regular Express Primer - (2007-05-20)
[1110] Python - two different splits - (2007-03-15)
[970] String duplication - x in Perl, * in Python and Ruby - (2006-12-07)
[954] Splitting Pythons in Bradford - (2006-11-29)
[943] Matching within multiline strings, and ignoring case in regular expressions - (2006-11-25)
[903] Pieces of Python - (2006-10-23)
[773] Breaking bread - (2006-06-22)
[560] The fencepost problem - (2006-01-10)
[463] Splitting the difference - (2005-10-13)
[324] The backtick operator in Python and Perl - (2005-05-25)
Some other Articles
Bowerhill, Melksham, 2006 CalendarGood IT training cannot be cheapWhy is Tomcat called Tomcat?I have a river to crossPython printfMore spam - a success storyMySQL - a score of things to rememberRunning a Perl script within a PHP pageNew Navigation Aid - Launch of My WellhoBeing atypical is typical