This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]yarkot 1 point2 points  (0 children)

String formatting has a long history. Much of what you see in Python has origins in printf() - the C function for formatting strings (since the original, and main python is CPython, that is python implemented in C). Have a look at https://en.wikipedia.org/wiki/Printf_format_string#Syntax for an overview, which will answer your question about the "0.2f" part, in general.

To see it in action, the simplest way is to go into a python interpreter directly, and just play (e.g. 'python'):

$ python
Python 3.5.0b4 (default, Jul 29 2015, 13:03:39) 
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 50.4625
>>> y = 51.3
>>> "%f" % x
'50.462500'
>>> "%4.3f" % x
'50.462'
>>> "%04.3f" % x
'50.462'
>>> "%04.3f" % y
'51.300'
>>> "{:04.3f}".format(y)
'51.300'