[英]Unexpected behavior of str.format()
I am using templates in this manner: 我以这种方式使用模板:
data = {'root':{'childrens':[1,2]}}
print('{data[root][childrens][0]}'.format(**locals()))
Output is 1
as expected, but when I run this code: 输出为
1
如预期的那样,但是当我运行此代码时:
print('{data[root][childrens][-1]}'.format(**locals()))
I get this exception: 我得到这个例外:
Traceback (most recent call last):
...
'{data[root][childrens][-1]}'.format(**locals())
TypeError: list indices must be integers or slices, not str
Explanation from PEP 3101 : PEP 3101的说明:
It should be noted that the use of 'getitem' within a format string is much more limited than its conventional usage. 应该注意的是,格式字符串中“ getitem”的使用比常规用法受到更多限制。 In the above example, the string 'name' really is the literal string 'name', not a variable named 'name'.
在上面的示例中,字符串“ name”实际上是文字字符串“ name”,而不是名为“ name”的变量。 The rules for parsing an item key are very simple.
解析项目密钥的规则非常简单。 If it starts with a digit, then it is treated as a number, otherwise it is used as a string.
如果以数字开头,则将其视为数字,否则将其用作字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.