Python - decimal places (putting floats into a string)

>>> variable = 12
>>> print 'blah, blah %4.3f' %variable
blah, blah 12.000
>>> print 'blah, blah %1.1f' %variable
blah, blah 12.0

Here is the Python Doc Link, please consider:

Since str.format() is quite new, a lot of Python code still uses the % operator. However, because this old style of formatting will eventually be removed from the language, str.format() should generally be used.


In Python version 2.6 and newer, you can use:

>>> print('blah, blah {0:.2f}'.format(variable))

where "0" refers to the first value passed into str.format, ":" says "here comes the format specification", and ".2f" means "floating point number with two decimal places of precision". This is the suggested way of formatting strings now.