我以这种方式使用模板:
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
来自PEP 3101的解释:
应该注意的是,在格式字符串中使用“getitem” 它的使用范围比传统的要有限得多。在上面的例子中, 字符串'name'实际上是文本字符串'name',而不是变量 名为“name”。解析项键的规则非常简单。 如果它以一个数字开头,那么它将被视为一个数字,否则 它被用作字符串。
基于doc:
-1
被认为是expression
,而不是integer
。你知道吗在这个question中也有有用的信息。你知道吗
相关问题 更多 >
编程相关推荐