String Formatting with new .format()

Michael Torrie torriem at gmail.com
Tue Mar 27 11:22:52 EDT 2018


On 03/26/2018 09:37 AM, Ganesh Pal wrote:
> Hi Team,
> 
> Just a quick suggestion, on string formatting with .format() which of the
> below is better , given both give the same result .

No they don't. Look more closely at the output.

>>>> attempts = 1
>>>> msg2 = "Hello"
>>>> print "Retry attempt:{0} for error:{1}".format(attempts,msg2)
> Retry attempt:1 for error:Hello
                    ^^^^^^^^^^^^^^^^^
> 
> OR
> 
>>>> attempts = 1
>>>> msg2 = "Hello"
>>>> print "Retry attempt:{0} for error:{0}".format(attempts,msg2)
> Retry attempt:1 for error:1
                    ^^^^^^^^^^
The second example places the same argument 0 in two places in your
string.  This is not what you want, I don't think.

> PS : This is the silly question but I wanted to know if it really makes any
> difference

What makes any difference?



More information about the Python-list mailing list