Python - decimal places (putting floats into a string)

前端 未结 3 1616
广开言路
广开言路 2021-01-18 02:17

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

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-18 03:18

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

提交回复
热议问题