str = 'I love %s and %s, he loves %s and %s.'
我想用这种格式显示
我喜欢苹果和音调,他喜欢苹果和音调。
请只添加两个变量,但需要一种方法在一个句子中使用它两次。
答案 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”之外的其他名字。 :)