print("%.2f" % total)

Chris Angelico rosuav at gmail.com
Sun Nov 22 02:21:46 EST 2015


On Sun, Nov 22, 2015 at 5:30 PM, Cai Gengyang <gengyangcai at gmail.com> wrote:
> What do the lines inside the parentheses in this statement print("%.2f" % total) mean ?
>
> What does "%.2f" % total represent ?
>

This is called "percent formatting" or "printf-style formatting". It's
a means of formatting a tuple of values (or in this case, a single
value) into a string; the percent sign introduces a format string, and
the letter (in this case 'f') ends it, and says what kind of
formatting to use. Everything else is just part of the string.

>>> "Hello, %s!" % "world"
'Hello, world!'
>>> "%d + %d = %o... in octal! I'M FINE!" % (4, 4, 8)
"4 + 4 = 10... in octal! I'M FINE!"

As you can see, you can play with this at the interactive prompt to
find out what's happening.

ChrisA



More information about the Python-list mailing list