python在一个字符串中包含多个%s
我想用这种格式来显示 我爱苹果和沥青,他爱苹果和沥青 请只添加两个变量,但需要一种方法在一句话中使用两次 使用口述:python在一个字符串中包含多个%s,python,string,Python,String,我想用这种格式来显示 我爱苹果和沥青,他爱苹果和沥青 请只添加两个变量,但需要一种方法在一句话中使用两次 使用口述: str = 'I love %s and %s, he loves %s and %s.' 或者使用2.6中引入的较新功能: >>> s = 'I love %(x)s and %(y)s, he loves %(x)s and %(y)s.' >>> s % {"x" : "apples", "y" : "oranges"} 'I lov
str = 'I love %s and %s, he loves %s and %s.'
或者使用2.6中引入的较新功能:
>>> 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.'
注意:调用变量str
会屏蔽内置函数
当然,您可以使用除“1”和“2”之外的其他名称:) 请永远不要调用变量
str
。有什么理由应该使用格式而不是字典?或者这只是个人喜好的问题?我相信.format
只是涵盖了更多的情况。这里提出了一个类似的问题:。我个人倾向于使用%
,以确保简洁性和性能,如果可读性得到改善,则使用.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 = '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.'