【发布时间】:2018-09-09 18:58:25
【问题描述】:
a = 19/3
print('just testing {a:1.4f}'.format (a))
在 python 3.5 中,这会导致错误 KeyError: 'a'。
我不明白为什么。我可以使用一种解决方法来克服错误,但如果有人能解释我为什么会收到错误,我将不胜感激。
【问题讨论】:
-
print('刚刚测试 {0:.4f}'.format (a))
a = 19/3
print('just testing {a:1.4f}'.format (a))
在 python 3.5 中,这会导致错误 KeyError: 'a'。
我不明白为什么。我可以使用一种解决方法来克服错误,但如果有人能解释我为什么会收到错误,我将不胜感激。
【问题讨论】:
类似字典的符号:
>>> a = 4
>>> b = 10
>>> 'just testing {num1}, {num2}'.format(num1 = a, num2 = b)
just testing 4, 10
顺序符号
>>> a = 4
>>> b = 10
>>> 'just testing {0}, {1}'.format(a, b)
just testing 4, 10
要么使用类似字典的符号:
print('just testing {num}'.format(num=a))
或顺序的:
print('just testing {0}'.format(a))
【讨论】:
冒号之前的项目是 format() 函数参数的索引。详情请见https://docs.python.org/3.5/library/stdtypes.html#str.format。
所以你的例子应该是:
a = 19/3
print('just testing {0:.4f}'.format (a))
或者,如果您运行的是 python 3.6 或更高版本,则可以使用 f-strings:
a = 19/3
print(f'just testing {a:.4f}')
详情请见https://docs.python.org/3/reference/lexical_analysis.html#f-strings
【讨论】:
print('just testing {0:.4f}'.format (a))
这里的变量索引从 0 开始。
所以如果你有另一个变量让我们说b=3.142
语法是:
print('just testing {1:.2f} {0:.4f}'.format (a,b))
【讨论】: