print & string formatting

Thomas Jollans tjol at tjol.eu
Sun Jul 22 04:54:26 EDT 2018


On 22/07/18 06:54, Cameron Simpson wrote:
> On 21Jul2018 21:33, Sharan Basappa <sharan.basappa at gmail.com> wrote:
>> I get a lot confused while using print functions in Python.
>>
>> For example, I get the same results for the following code:
>>
>> str = "one two three"
> 
> Pleasetry not to name variables after builtin classes ("str" is the name
> of Python's string class).
> 
>> print str
>> print "%s" %(str)
>>
>> So, what is the need to use the second method which I see being used
>> in many programs I am referring to
> 
> For a bare "%s", one would normally just write str(s) where "s" is your
> string variable.
> 
> The % formatting is usually for (a) more complex messages or (b)
> separating the message format from the values. Example:
> 
>  print("The time is %s and the place is %s." % (when, where))
> 
> Instead of the much harder to read and maintain:
> 
>  print("The time is", str(when), "and the place is", str(where), ".")

Also, the output is different (there's an extra space before the full stop)

> 
> Cheers,
> Cameron Simpson <cs at cskk.id.au>


More information about the Python-list mailing list