Python-小数位数(将浮点数放入字符串中) [英] Python - decimal places (putting floats into a string)

查看:265
本文介绍了Python-小数位数(将浮点数放入字符串中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用以下格式:

I have been using the format:

print 'blah, blah %f' %variable

将变量放入字符串中.我听说它比"+ str()+"方法更具Python风格,并且已经习惯了. 有没有一种方法可以指定用%f添加到字符串的小数位?在提供变量之前,我尝试过将数字四舍五入.

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.

谢谢

推荐答案

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

这是 Python文档链接,请考虑:

由于str.format()很新,因此许多Python代码仍然使用% 操作员.但是,因为这种旧的格式设置格式 最终将其从语言中删除,通常应将str.format() 被使用.

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.

这篇关于Python-小数位数(将浮点数放入字符串中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆