Python - 小数位(将浮点数放入字符串)

Ana*_*ake 6 python string floating-point

我一直在使用这种格式:

print 'blah, blah %f' %variable
Run Code Online (Sandbox Code Playgroud)

将变量放入字符串.我听说它比'+ str()+'方法更加pythonic,并且已经习惯了它.有没有办法用%f指定添加到字符串的小数位?我在提供变量之前尝试过舍入数字.

谢谢

Jac*_*cob 10

>>> variable = 12
>>> print 'blah, blah %4.3f' %variable
blah, blah 12.000
>>> print 'blah, blah %1.1f' %variable
blah, blah 12.0
Run Code Online (Sandbox Code Playgroud)

这是Python Doc Link,请考虑:

由于str.format()很新,很多Python代码仍然使用%运算符.但是,因为最终将从语言中删除这种旧格式化格式,所以通常应该使用str.format().

  • 希望他们能够保留它,它的编码速度肯定更快,而且不那么烦人! (2认同)

Kir*_*ser 6

在 Python 2.6 及更新版本中,您可以使用:

>>> print('blah, blah {0:.2f}'.format(variable))
Run Code Online (Sandbox Code Playgroud)

其中“0”表示传入 str.format 的第一个值,“:”表示“格式规范来了”,“.2f”表示“具有两位小数精度的浮点数”。这是现在格式化字符串的建议方法。