为什么 string.format() 字典引用中不需要 '?
Why no ' is needed in string.format() dictionary reference?
my_dic={"Vajk":"vékony","Bibi":'magas'}
my_dic['Bibi']
'magas'
我们可以看到,我们需要 ' 来引用键 'Bibi' 的值。但如果想在 .format() 中使用相同的格式,则会出现此错误:
print("úgy érzem, hogy Bibi nagyon {0['Bibi']}".format(my_dic))
Traceback (most recent call last):
File "<ipython-input-109-52760dad9136>", line 1, in <module>
print("úgy érzem, hogy Bibi nagyon {0['Bibi']}".format(my_dic))
KeyError: "'Bibi'"
我必须使用不带 ' 的引用,然后才有效。
print("úgy érzem, hogy Bibi nagyon {0[Bibi]}".format(my_dic))
úgy érzem, hogy Bibi nagyon magas
为什么第一个不行,为什么第二个不行?应该相反,第一个应该起作用,第二个不应该。
It should be the opposite, first should work, and second shouldn't.
不,不应该,因为双引号字符串中的 'Bibi'
是带引号的字符串,而不仅仅是 Bibi
。您可以按以下方式简单地检查一下:
In [51]: "'Bibi'" == "Bibi"
Out[51]: False
如果在第一种情况下密钥是 "'Bibi'"
那么它就完美地工作了:
In [49]: my_dic={"Vajk":"vékony","'Bibi'":'magas'}
In [50]: print("úgy érzem, hogy Bibi nagyon {0['Bibi']}".format(my_dic))
úgy érzem, hogy Bibi nagyon magas
为什么它在第一种情况下不接受 "Bibi"
并且没有给你预期结果的原因是 Python 在字典中查找括号之间的所有内容,在这种情况下括号内有 "'Bibi'"
而不是 'Bibi'
.
首先,一些术语:
'Bibi'
是一个 字符串文字 ,用于创建字符串值的语法。您的键是字符串,您可以使用字符串文字指定其中一个键。
您可以改用变量;将字符串值分配给变量并使用该变量从字典中获取项目:
foo = 'Bibi' # or read this from a file, or from a network connection
print(my_dic[foo]) # -> magas
在字符串格式中,{...}
是 替换字段 。 str.format()
方法为替换字段提供值。
{...}
替换字段语法中的 0[Bidi]
部分是 字段名称 。当您在字段名称中使用 [...]
时,它是一个复合字段名称(有多个部分)。 [...]
语法通常称为索引。
字段名称中使用的格式刻意保持简单,仅 Python- 类似于 。语法被简化以限制它的用途,将功能限制为通常可以安全使用的东西。
因此,如果您使用带有 getitem [...]
索引语法的复合名称,名称将被视为字符串,但您不会使用引号来创建字符串。无论如何你不能传入一个变量名,没有必要在 'name'
(一个字符串)和 name
(一个变量)之间进行对比。
换句话说,在 Python 表达式中,my_dic[foo]
通过查找变量 foo
的值来工作,这与使用像这样的字符串文字是不同的概念my_dic['Bidi']
。但是你不能在字段名中使用变量,在str.format()
操作中,使用{0[foo]}
应该永远找不到变量foo
.
原文proposal to add the feature解释为:
Unlike some other programming languages, you cannot embed arbitrary expressions in format strings. This is by design - the types of expressions that you can use is deliberately limited. Only two operators are supported: the '.' (getattr) operator, and the '[]' (getitem) operator. The reason for allowing these operators is that they don't normally have side effects in non-pathological code.
和
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.
保持语法简单可使模板更安全。来自 Security Considerations section:
Barring that, the next best approach is to ensure that string formatting has no side effects. Because of the open nature of Python, it is impossible to guarantee that any non-trivial operation has this property. What this PEP does is limit the types of expressions in format strings to those in which visible side effects are both rare and strongly discouraged by the culture of Python developers.
允许 {0[foo]}
在当前范围内查找变量很容易产生副作用,而将 foo
视为字符串意味着您可以确定地知道它永远是字符串 'foo'
而不是其他东西。
如果您 仅 使用字符串文字而不是动态值(因此 'some {} template'.format(...)
而不是 some_variable.format(...)
,并且您正在使用 Python 3.6 或更新版本,您可以使用 formatted string literals 代替,因为您可以使用完整的 Python 表达式:
print(f"úgy érzem, hogy Bibi nagyon {my_dic['Bibi']}")
在 f
字符串中,您使用实际的 Python 表达式而不是字段名称,因此您再次使用引号来传递字符串文字。因为它们是字符串文字,所以会在定义它们的地方进行计算,作为开发人员,您可以看到哪些局部变量可用,因此您可能知道如何确保其安全。
my_dic={"Vajk":"vékony","Bibi":'magas'}
my_dic['Bibi']
'magas'
我们可以看到,我们需要 ' 来引用键 'Bibi' 的值。但如果想在 .format() 中使用相同的格式,则会出现此错误:
print("úgy érzem, hogy Bibi nagyon {0['Bibi']}".format(my_dic))
Traceback (most recent call last):
File "<ipython-input-109-52760dad9136>", line 1, in <module>
print("úgy érzem, hogy Bibi nagyon {0['Bibi']}".format(my_dic))
KeyError: "'Bibi'"
我必须使用不带 ' 的引用,然后才有效。
print("úgy érzem, hogy Bibi nagyon {0[Bibi]}".format(my_dic))
úgy érzem, hogy Bibi nagyon magas
为什么第一个不行,为什么第二个不行?应该相反,第一个应该起作用,第二个不应该。
It should be the opposite, first should work, and second shouldn't.
不,不应该,因为双引号字符串中的 'Bibi'
是带引号的字符串,而不仅仅是 Bibi
。您可以按以下方式简单地检查一下:
In [51]: "'Bibi'" == "Bibi"
Out[51]: False
如果在第一种情况下密钥是 "'Bibi'"
那么它就完美地工作了:
In [49]: my_dic={"Vajk":"vékony","'Bibi'":'magas'}
In [50]: print("úgy érzem, hogy Bibi nagyon {0['Bibi']}".format(my_dic))
úgy érzem, hogy Bibi nagyon magas
为什么它在第一种情况下不接受 "Bibi"
并且没有给你预期结果的原因是 Python 在字典中查找括号之间的所有内容,在这种情况下括号内有 "'Bibi'"
而不是 'Bibi'
.
首先,一些术语:
'Bibi'
是一个 字符串文字 ,用于创建字符串值的语法。您的键是字符串,您可以使用字符串文字指定其中一个键。您可以改用变量;将字符串值分配给变量并使用该变量从字典中获取项目:
foo = 'Bibi' # or read this from a file, or from a network connection print(my_dic[foo]) # -> magas
在字符串格式中,
{...}
是 替换字段 。str.format()
方法为替换字段提供值。{...}
替换字段语法中的0[Bidi]
部分是 字段名称 。当您在字段名称中使用[...]
时,它是一个复合字段名称(有多个部分)。[...]
语法通常称为索引。
字段名称中使用的格式刻意保持简单,仅 Python- 类似于 。语法被简化以限制它的用途,将功能限制为通常可以安全使用的东西。
因此,如果您使用带有 getitem [...]
索引语法的复合名称,名称将被视为字符串,但您不会使用引号来创建字符串。无论如何你不能传入一个变量名,没有必要在 'name'
(一个字符串)和 name
(一个变量)之间进行对比。
换句话说,在 Python 表达式中,my_dic[foo]
通过查找变量 foo
的值来工作,这与使用像这样的字符串文字是不同的概念my_dic['Bidi']
。但是你不能在字段名中使用变量,在str.format()
操作中,使用{0[foo]}
应该永远找不到变量foo
.
原文proposal to add the feature解释为:
Unlike some other programming languages, you cannot embed arbitrary expressions in format strings. This is by design - the types of expressions that you can use is deliberately limited. Only two operators are supported: the '.' (getattr) operator, and the '[]' (getitem) operator. The reason for allowing these operators is that they don't normally have side effects in non-pathological code.
和
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.
保持语法简单可使模板更安全。来自 Security Considerations section:
Barring that, the next best approach is to ensure that string formatting has no side effects. Because of the open nature of Python, it is impossible to guarantee that any non-trivial operation has this property. What this PEP does is limit the types of expressions in format strings to those in which visible side effects are both rare and strongly discouraged by the culture of Python developers.
允许 {0[foo]}
在当前范围内查找变量很容易产生副作用,而将 foo
视为字符串意味着您可以确定地知道它永远是字符串 'foo'
而不是其他东西。
如果您 仅 使用字符串文字而不是动态值(因此 'some {} template'.format(...)
而不是 some_variable.format(...)
,并且您正在使用 Python 3.6 或更新版本,您可以使用 formatted string literals 代替,因为您可以使用完整的 Python 表达式:
print(f"úgy érzem, hogy Bibi nagyon {my_dic['Bibi']}")
在 f
字符串中,您使用实际的 Python 表达式而不是字段名称,因此您再次使用引号来传递字符串文字。因为它们是字符串文字,所以会在定义它们的地方进行计算,作为开发人员,您可以看到哪些局部变量可用,因此您可能知道如何确保其安全。