New Python 3.0 string formatting - really necessary?

Arnaud Delobelle arnodel at googlemail.com
Mon Dec 22 17:36:15 EST 2008


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:

> Instead of just whinging, how about making a suggestion to fix it? Go on, 
> sit down for an hour or ten and try to work out how a BINARY OPERATOR 
> like % (that means it can only take TWO arguments) can deal with an 
> arbitrary number of arguments, *without* having any special cases.
>
> Go on. Take your time. I'll be waiting.

Well that's easy.  I see 'r' didn't answer so I will: only accept tuples
on the right hand side of the %, so all arguments have to be put inside
a tuple.

>>> "%s" % 42
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for %: 'str' and 'int'
>>> "%s" % (42,)
'42'

Of course there would still be the possibility of uncaught bugs when
people forget to put the argument in a tuple if the argument itself is a
tuple of length 1.

>>> def foo(x):
...     print "foo(%s)" % x
...     # should be     % (x,)
... 
>>> foo('a')
TypeError: unsupported operand type(s) for %: 'str' and 'str'
>>> # But if x is a tuple of length 1 the error is not reported
>>> foo((1,))
foo(1)

That's why .format() is a better option IMHO.

-- 
Arnaud



More information about the Python-list mailing list