syntax difference
Ben Finney
ben+python at benfinney.id.au
Sun Jun 17 01:30:24 EDT 2018
Sharan Basappa <sharan.basappa at gmail.com> writes:
> I think I am now confused with format options in Python.
You should refer to the documentation for string formatting
<URL:https://docs.python.org/3/library/stdtypes.html#str.format>
<URL:https://docs.python.org/3/library/string.html#formatstrings>
(or, if you want to continue with the older less-flexible style,
<URL:file:///usr/share/doc/python3/html/library/stdtypes.html#printf-style-string-formatting>)
> I tried an example as below and both print proper value:
>
> age = 35
>
> print "age is %s" % age
The ‘s’ format specifier says “Ask the object for its text
representation, and put that text here”.
Every object has a text representation, so ‘s’ works with any object.
> print "age is %d" % age
The ‘d’ format specifier says “Format the integer as a decimal text
representation, and put that text here”.
Only objects that are integers (or that implement the format-as-decimal
API) will work with ‘d’.
> I other languages I know the format specifier should be same as the
> variable type. For example, in the above case, it has to be %d and not
> %s
Because you are explicitly specifying which formatting to use, there's
no ambiguity. With an object that is an integer, either of the above
makes sense in different use cases.
--
\ “A right is not what someone gives you; it's what no one can |
`\ take from you.” —Ramsey Clark |
_o__) |
Ben Finney
More information about the Python-list
mailing list