( (value_in_dictionary) modulo[%] (dictionary) ) 在 Python 中有什么作用?

Kar*_*pta 1 python dictionary modulo string-interpolation python-3.x

我想了解有什么value_in_dictionary % dictionary作用。

我试过

values = {
    'hello':'world',
    'hello2':'world2',
}
value = 'world'
print(value % values)
Run Code Online (Sandbox Code Playgroud)

这打印

world
Run Code Online (Sandbox Code Playgroud)

Mad*_*ist 6

对于字符串,取模会触发旧式字符串插值。右手操作数可以是标量、元组或字典。

文档内容如下:

当正确的参数是字典(或其他映射类型)时,字符串中的格式必须包含一个带括号的映射键,该键插入到该'%'字符后立即插入的字典中。映射键从映射中选择要格式化的值。例如:

>>> print('%(language)s has %(number)03d quote types.' %
...       {'language': "Python", "number": 2})
Python has 002 quote types.
Run Code Online (Sandbox Code Playgroud)

您的特定示例中没有格式,因此没有插入任何内容。添加一个有效的插值键,例如world = 'hello %(hello)'world = 'hello %(hello2)'将说明它是如何工作的。尝试world = 'hello %(hello3)'将导致KeyError.