在Python 2.6中打印浮点数的str.format()错误

时间:2015-04-08 09:11:16

标签: python string-formatting python-2.6

我试图使用Python的str.format()打印一些浮点数。这是一个示例代码

table = {'pi':3.1415926}
for variable, value in table.items():
    print '{0:10} ==> {0:.2f}'.format(variable, value)

我这样做时出现以下错误

ValueError: Unknown format code 'f' for object of type 'str'

我不明白为什么Python认为3.1415926是一个字符串。

感谢。

2 个答案:

答案 0 :(得分:3)

你有向后的职位:

table = {'pi':3.1415926}
for variable, value in table.items():
    print '{0} ==> {1:.2f}'.format(variable, value)

pi ==> 3.14

或者只是删除变量,除非你真的要打印pi并迭代值:

for  value in table.values():
    print '{0} ==> {0:.2f}'.format(value)

3.1415926 ==> 3.14

你也可以使用带有**的字典:

table = {'pi':3.1415926}

print '{pi} ==> {pi:.2f}'.format(**table)

答案 1 :(得分:3)

当你写{0}时,它引用格式函数的第一个参数。您需要将其更改为1.

table = {'pi':3.1415926}
for variable, value in table.items():
    print '{0:10} ==> {1:.2f}'.format(variable, value)

编辑关注@ AshwiniChaudhary的评论 - 在 Python 2.7 中,您甚至不需要指定数字,它会自动按顺序使用它们

table = {'pi':3.1415926}
for variable, value in table.items():
    print '{:10} ==> {:.2f}'.format(variable, value)
相关问题