Python中字符串中多个%s的用法

9 投票
2 回答
14226 浏览
提问于 2025-04-16 08:29
str = 'I love %s and %s, he loves %s and %s.' 

我想用这个格式来展示内容。

我喜欢苹果和梨,他也喜欢苹果和梨。

只需要添加两个变量,但需要一种方法在一句话中使用两次。

2 个回答

6
>>> str = 'I love %(1)s and %(2)s, he loves %(1)s and %(2)s.' % {"1" : "apple", "2" : "pitch"}
>>> str
'I love apple and pitch, he loves apple and pitch.'

当然,你可以使用除了'1'和'2'以外的其他名字。:)

25

使用字典:

>>> s = 'I love %(x)s and %(y)s, he loves %(x)s and %(y)s.'
>>> s % {"x" : "apples", "y" : "oranges"}
'I love apples and oranges, he loves apples and oranges.'

或者可以使用更新的 format 函数,这个函数在 Python 2.6 版本中引入的:

>>> s = 'I love {0} and {1}, she loves {0} and {1}'
>>> s.format("apples", "oranges")
'I love apples and oranges, she loves apples and oranges'

注意:如果你把一个变量命名为 str,会覆盖掉内置的 str([object]) 函数。

撰写回答