关于字符串中多个%s的python

时间:2010-12-14 01:36:13

标签: python string

str = 'I love %s and %s, he loves %s and %s.' 

我想用这种格式显示

我喜欢苹果和音调,他喜欢苹果和音调。

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

2 个答案:

答案 0 :(得分:25)

使用dict:

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

或者使用2.6:

中引入的较新的format函数
>>> 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])

答案 1 :(得分: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”之外的其他名字。 :)