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

What does ( (value_in_dictionary) modulo[%] (dictionary) ) does in Python?

我想了解 value_in_dictionary % dictionary 的作用。

我试过了

values = {
    'hello':'world',
    'hello2':'world2',
}
value = 'world'
print(value % values)

这会打印

world

对于字符串,取模触发器 old style string interpolation。右手操作数可以是标量、元组或字典。

文档内容如下:

When the right argument is a dictionary (or other mapping type), then the formats in the string must include a parenthesised mapping key into that dictionary inserted immediately after the '%' character. The mapping key selects the value to be formatted from the mapping. For example:

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

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