((value_in_dictionary)modulo [%](dictionary))在Python中做什么?

问题描述 投票:1回答:1

想了解(value_in_dictionary%词典)的工作。

已尝试

values = {
          'hello':'world',
          'hello2':'world2',
          }
value = 'world'

ans = value % values

print(ans)

返回

world
python python-3.x dictionary modulo
1个回答
3
投票

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

文档内容如下:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.