Labels

new blog 2.0

2009/02/20

% percent string formatting in Python

Playing around with string formatting in Python I made an interesting discovery. Python supports extended string formatting similar to the one introduced in C, but much more powerful. It does it by means of using a % (percent) sign optionally followed by name in brackets (which can be a dictionary key), formatting flags, unit width, a dot with precision point and finally mandatory character code for formatted unit's type. General definition looks as follows:
'preceding text %[(key)][flags][width][.precision point] following text' % value
and if you want to feed a string with a literal percentage sign you use '%%' (double percentage)... but there is a catch! The double-percentage rule is only valid for strings that are about to be injected values by format strings; strings that are not meant to be formatted should contain only one percentage sign to reach the same outcome. In other words the following lines of code produce the same output:
print '%% %s' % 'hello'
print '% hello'
whereby
print '%% %s' % 'hello'
print '%% hello'
causes the second line to print out the percentage sign twice, and
print '% %s' % 'hello'
is wrong and errors out with 'TypeError: not all arguments converted during string formatting'. This behaviour is diffrent from the C one, where all strings, formatted or not are treated equally.

No comments: