new string-formatting preferred? (was "What is this syntax ?")

Terry Reedy tjreedy at udel.edu
Mon Jun 20 22:17:07 EDT 2011


On 6/20/2011 8:46 PM, Tim Chase wrote:
> On 06/20/2011 05:19 PM, Ben Finney wrote:
>> “This method of string formatting is the new standard in
>> Python 3.0, and should be preferred to the % formatting
>> described in String Formatting Operations in new code.”
>>
>> <URL:http://docs.python.org/library/stdtypes.html#str.format>
>
> Is there a good link to a thread-archive on when/why/how .format(...)
> became "preferred to the % formatting"?

That is a controversial statement.

 > I haven't seen any great wins of
> the new formatting over the classic style. Is there some great feature
> of new-style formatting that I've missed out on that obviates bajillions
> of lines of 2.x code?

It does not abuse the '%' operator, it does not make a special case of 
tuples (a source of bugs), and it is more flexible, especially 
indicating objects to be printed. Here is a simple example from my code 
that would be a bit more difficult with %.

multi_warn = '''\
Warning: testing multiple {0}s against an iterator will only test
the first {0} unless the iterator is reiterable; most are not.'''.format
...
print(multiwarn('function'))
...
print(multiwarn('iterator'))

Here is a more complex example:

class chunk():
	def __init__(self, a, b):
		self.a,self.b = a,b
c=chunk(1, (3,'hi'))
print('{0.__class__.__name__} object has attributes int a <{0.a}> and 
tuple b with members <{0.b[0]}> and <{0.b[1]}>'.format(c))
 >>>
chunk object has attributes int a <1> and tuple b with members <3> and <hi>

-- 
Terry Jan Reedy





More information about the Python-list mailing list