Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python2.6中打印浮动的str.format()错误_Python_String Formatting_Python 2.6 - Fatal编程技术网

Python2.6中打印浮动的str.format()错误

Python2.6中打印浮动的str.format()错误,python,string-formatting,python-2.6,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的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是一个字符串


谢谢。

您的位置向后:

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
您也可以将dict与**一起使用:

table = {'pi':3.1415926}

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

写入{0}时,它引用format函数的第一个参数。您需要将其更改为1

table = {'pi':3.1415926}
for variable, value in table.items():
    print '{0:10} ==> {1:.2f}'.format(variable, value)
编辑以下@AshwiniChaudhary的注释-在Python2.7中,您甚至不需要指定数字,它将按顺序自动使用它们

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

@lost.identity,别担心,你真的想打印pi吗?是的,这只是我写的一个小样本代码。我打算打印一个字符串而不是圆周率。现在它工作了!Python2.6不支持格式字符串的自动编号,因此第一个选项不起作用。谢谢,这非常有用,但正如Ashwini提到的,它不适用于2。6@AshwiniChaudhary你说得对,我没注意。根据您的评论进行编辑