[Tutor] output formatting question

Steven D'Aprano steve at pearwood.info
Mon Aug 10 05:42:22 CEST 2015


On Wed, Aug 05, 2015 at 09:08:16PM -0700, tom arnall wrote:
> i have read --  with what i think is a reasonable amount of attention
> -- all of the doc' i can find about string formatting in python. for
> the life of me, i cannot see how any of the other methods do more than
> you can do with, to use a concrete example:
> 
>     print "Here %s a number: %3d" % ("is",  1)
> 
>     #OR:
> 
>     s =   "Here %s a number: %3d" % ("is", 1)
>     print s
> 
> what am i not getting?

%s and %r work with any object at all. Or do they? Run 
this code snippet to find out:

objects = [ 1, "a", 2.5, None, [1,2], (1,2) ]
for o in objects:
    print "the object is: %s" % o


With positional arguments, % formatting operates strictly left to right, 
while the format() method lets you operate on arguments in any order, 
and you can refer to the same item multiple times:

py> "{1} {0} {0}".format("first", "second")
'second first first'

Compared to:

"%s %s %s" % ("second", "first", "first")

which is inconvenient and annoying.


% formatting allows you to use positional arguments or keyword 
arguments, but not both at the same time. The format() method allows 
both at the same time:

py> "{1} {0} {spam}".format("first", "second", spam="third")
'second first third'

The format() method also supports customization via the special method 
__format__, although I haven't done this and I'm not sure how it works. 
But I think it means that you can invent your own formatting codes.

The format() method also supports centring with the ^ alignment option, 
thousands separators with , and a few other additional features, e.g. 
binary output:

py> "{:b}".format(3000)
'101110111000'

There's no doubt that the format() method is significantly more powerful 
than % interpolation, but its also slower, and for many purposes good 
old fashioned % is perfectly fine.



-- 
Steve


More information about the Tutor mailing list