我正在学习python,我对格式化的“新样式”不太了解。这是我的代码:
>>> 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中什么有效,什么无效。
'{0[n]}...'
format()
format
O[n] 不是字符串,而是python表达式。当python解析它时,它试图解析 n 作为变量,在您的情况下,它不存在。如果你执行的话,你的尝试会成功的 n='n' 在查找之前。
O[n]
n
n='n'