python 中带有字典的新样式格式

new style formating in python with dictionaries

我正在学习 python,但我对格式化的 'new style' 不太了解。这是我的代码:

>>> d={'n':32,'f':5.03,'s':'test string'}
>>> '{0[n]} {0[f]} {0[s]} {1}'.format(d, 'other')
'32 5.03 test string other'

但是当我在控制台中输入时:

>>> d[n]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
>>> d['n']
32

那么为什么在格式化字符串中,不带引号的 0[n] 能够从字典中读取带有键 'n' 的值(在本例中键是一个字符串)但是当我在控制台试过了,没用。

另外,如果键不是字符串会怎样?

谢谢

'{0[n]}...' 是由方法 format() 解释的字符串。 Python 解析器不关心该字符串的内容,并且 format 可以使用任何符号,无论什么在 Python 中有效,什么无效。

O[n] 不是字符串,它是 Python 表达式。当 Python 解析它时,它会尝试将 n 解析为一个变量,在您的情况下,该变量不存在。如果您在查找之前执行 n='n',您的尝试将会成功。