簡體   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