Python - decimal places (putting floats into a string)

前端 未结 3 1617
广开言路
广开言路 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:10

    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.

提交回复
热议问题