3 回答

TA贡献1836条经验 获得超4个赞
对于Python <3(例如2.6 [请参见注释]或2.7),有两种方法可以实现。
# Option one
older_method_string = "%.9f" % numvar
# Option two
newer_method_string = "{:.9f}".format(numvar)
但请注意,对于高于3的Python版本(例如3.2或3.3),首选选项2 。
有关选项二的更多信息,我建议使用Python文档中有关字符串格式的链接。
有关选项一的更多信息,此链接就足够了,并且具有有关各种标志的信息。
Python 3.6(于2016年12月正式发布)添加了f字符串文字,请参见此处的更多信息,它扩展了str.format方法(使用花括号来f"{numvar:.9f}"解决原始问题),即,
# Option 3 (versions 3.6 and higher)
newest_method_string = f"{numvar:.9f}"
解决了问题。查看@ Or-Duan的答案以获取更多信息,但是这种方法很快。

TA贡献1828条经验 获得超6个赞
Python 3.6 | 2017年
为了清楚起见,您可以使用f字符串格式。它的语法几乎与format方法相同,但是要好一些。
例:
print(f'{numvar:.9f}')

TA贡献1840条经验 获得超5个赞
使用round:
>>> numvar = 135.12345678910
>>> str(round(numvar, 9))
'135.123456789'
添加回答
举报