string formatting
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri May 6 22:30:53 EDT 2011
On Fri, 06 May 2011 14:39:15 -0500, harrismh777 wrote:
> On the other hand, consider this 3.x code snip:
>
> print("the %s is %d" % ('sky', 'blue'))
>
>
> That formatting will throw an exception, because the format
> construct is restricting the format entry to be a number, which 'blue'
> clearly isn't....
Er, yes. That's clearly deliberate, because the target uses %d rather
than %s. If the author wanted to accept anything, she would used %r or %s.
You might as well argue that:
print("the {} is {}".format('sky', int(x)))
is wrong, because if you leave the int out, any object can be used.
> The following print() is better, because *any* time or *most* types
> can be substituted and the 'polymorphism' of Python kicks in allowing
> for that, as so:
>
> print("the {} is {}".format('sky', 3.4))
This is not comparing apples with apples. The format equivalent is:
print("the {} is {:d}".format('sky', 'blue'))
which will also raise an exception, ValueError instead of TypeError.
--
Steven
More information about the Python-list
mailing list