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

use*_*652 9 python string

str = 'I love %s and %s, he loves %s and %s.' 
Run Code Online (Sandbox Code Playgroud)

我想用这种格式来显示

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

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

mik*_*iku 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.'
Run Code Online (Sandbox Code Playgroud)

或者使用format2.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'
Run Code Online (Sandbox Code Playgroud)

注意:调用变量str会掩盖内置函数str([object]).


Rue*_*uel 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.'
Run Code Online (Sandbox Code Playgroud)

当然你可以使用"1"和"2"之外的其他名称.:)