如果字典有一个存储为字符串的整数键 {'0': 'foo'}
您将如何在 Compound Field Names 中引用它使用 .format()
?
我知道它可能不是 pythonic (和糟糕的编程) 有一个带有这样的键的字典......但在这种情况下,也不可能使用这种方式:
>>> a_dict = {0: 'int zero',
... '0': 'string zero',
... '0start': 'starts with zero'}
>>> a_dict
{0: 'int zero', '0': 'string zero', '0start': 'starts with zero'}
>>> a_dict[0]
'int zero'
>>> a_dict['0']
'string zero'
>>> " 0 is {0[0]}".format(a_dict)
' 0 is int zero'
>>> "'0' is {0['0']}".format(a_dict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: "'0'"
>>> "'0start' is {0[0start]}".format(a_dict)
"'0start' is starts with zero"
{0[0]}.format(a_dict)
将始终引用键 int 0
即使没有,所以至少这是一致的:
>>> del a_dict[0]
>>> a_dict
{'0': 'string zero', '0start': 'starts with zero'}
>>> "{0[0]}".format(a_dict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 0L
(是的,我知道如果需要的话我可以做 '%s' % a_dict['0']
。)
最佳答案
str.format
,不同于例如"f-strings" ,不使用完整的解析器。拉出 grammar 的相关位:
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name ::= arg_name ("." attribute_name | "[" element_index "]")*
element_index ::= digit+ | index_string
index_string ::= <any source character except "]"> +
用方括号包围的 field_name
是一个 element_index
,它是:
- 一个或多个数字(
digit+
,如0
- 但前提是它们都是所有数字,这就是为什么0start
属于第二种情况);或 - 一系列 “除“]”之外的任何源字符。
因此对于 0['0']
field_name
是 "'0'"
,不是 '0'
。
... an expression of the form
'[index]'
does an index lookup using__getitem__()
.
对于 "'0' is {0['0']}".format(a_dict)
替换为 a_dict.__getitem__("'0'")
,并且在语法中无法选择实际的 a_dict['0']
。
关于python - 使用字典和复合字段 format() 并将整数键存储为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66162386/