string formatting

Ian Kelly ian.g.kelly at gmail.com
Fri May 6 15:54:52 EDT 2011


On Fri, May 6, 2011 at 1:39 PM, harrismh777 <harrismh777 at charter.net> wrote:
> harrismh777 wrote:    OP wrote:
>
>> (1) "the %s is %s" % ('sky', 'blue')
>>
>> (2) "the {0} is {1}".format('sky', 'blue')
>>
>> (3) "the {} is {}".format('sky', 'blue')
>
>   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....

If you used %d, then that exception is presumably what you wanted.  If
not, then you should just do:

print("the %s is %s" % ('sky', 'blue'))

>   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:

'%s' has exactly the same degree of polymorphism as '{}', because both
simply call str() on their argument.  There are good reasons to use
format instead of % if possible, but polymorphism isn't one of them.



More information about the Python-list mailing list