繁体   English   中英

str.format()的异常行为

[英]Unexpected behavior of str.format()

我以这种方式使用模板:

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

基于doc

element_index     ::=  integer | index_string

-1被视为一个expression ,而不是integer

在这个问题上也有有用的信息。

PEP 3101的说明:

应该注意的是,格式字符串中“ getitem”的使用比常规用法受到更多限制。 在上面的示例中,字符串“ name”实际上是文字字符串“ name”,而不是名为“ name”的变量。 解析项目密钥的规则非常简单。 如果以数字开头,则将其视为数字,否则将其用作字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM