string formatting

harrismh777 harrismh777 at charter.net
Fri May 6 15:39:15 EDT 2011


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

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

     print("the {} is {}".format('sky', 'blue'))


     l=['cloudy', 'today']
     print("the {} is {}".format('sky', l))


    On the other hand,....     :)


kind regards,
m harris



More information about the Python-list mailing list