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

时间:2019-01-19 19:11:58

标签: python string-formatting

我正在学习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'的值(在这种情况下,键是字符串),但是当我在控制台,它没有用。

此外,如果键不是字符串怎么办?

谢谢

1 个答案:

答案 0 :(得分:1)

<tr class="drop-file"> <td class="myFiles">1.png</td> <td class="myFiles">2.png</td> <td class="myFiles">3.png</td> </tr> 是由方法'{0[n]}...'解释的字符串。 Python解析器不关心该字符串的内容,而format()可以使用任何符号,无论在Python中什么有效或什么无效。

format不是字符串,而是Python表达式。当Python解析它时,它将尝试将O[n]解析为一个变量,在您的情况下,该变量不存在。如果您在查询之前执行了n,那么您的尝试就会奏效。