简体   繁体   中英

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:

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

Based on doc :

element_index     ::=  integer | index_string

-1 is deemed to be an expression , not an integer .

Also there is usefull information in this question .

Explanation from PEP 3101 :

It should be noted that the use of 'getitem' within a format string is much more limited than its conventional usage. In the above example, the string 'name' really is the literal string 'name', not a variable named '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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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