print & string formatting

Cameron Simpson cs at cskk.id.au
Sun Jul 22 00:54:41 EDT 2018


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), ".")

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


More information about the Python-list mailing list