Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - decimal places (putting floats into a string)

I have been using the format:

print 'blah, blah %f' %variable

to put variables into strings. I heard it was more pythonic than the '+str()+' approach, and have got quite used to it. Is there a way of specifying the decimal places added to the string with %f? I have tried rounding the number before supplying the variable.

Thanks

like image 243
Anake Avatar asked Jul 11 '11 11:07

Anake


1 Answers

>>> 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.

like image 109
Jacob Avatar answered Sep 21 '22 19:09

Jacob