str.format()的意外行为

2024-04-26 04:24:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我以这种方式使用模板:

data = {'root':{'childrens':[1,2]}}
print('{data[root][childrens][0]}'.format(**locals()))

输出如预期的1,但是当我运行此代码时:

print('{data[root][childrens][-1]}'.format(**locals()))

我有个例外:

Traceback (most recent call last):
...
    '{data[root][childrens][-1]}'.format(**locals())
TypeError: list indices must be integers or slices, not str

Tags: 代码模板formatmostdata方式rootcall
2条回答

来自PEP 3101的解释:

应该注意的是,在格式字符串中使用“getitem” 它的使用范围比传统的要有限得多。在上面的例子中, 字符串'name'实际上是文本字符串'name',而不是变量 名为“name”。解析项键的规则非常简单。 如果它以一个数字开头,那么它将被视为一个数字,否则 它被用作字符串。

基于doc

element_index     ::=  integer | index_string

-1被认为是expression,而不是integer。你知道吗

在这个question中也有有用的信息。你知道吗

相关问题 更多 >