格式化string时多次插入相同的值

我有一个这种forms的string

s='arbit' string='%s hello world %s hello world %s' %(s,s,s) 

string中的所有%s都具有相同的值(即s)。 有没有更好的方式来写这个? (而不是列出三个)

您可以使用Python 2.6和Python 3.x中提供的高级string格式 :

 incoming = 'arbit' result = '{0} hello world {0} hello world {0}'.format(incoming) 
 incoming = 'arbit' result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming} 

您可能希望阅读以获得理解: string格式化操作 。

您可以使用字典types的格式:

 s='arbit' string='%(key)s hello world %(key)s hello world %(key)s' % {'key': s,} 

取决于你的意思是更好的。 如果您的目标是删除冗余,这将起作用。

 s='foo' string='%s bar baz %s bar baz %s bar baz' % (3*(s,)) 
 >>> s1 ='arbit' >>> s2 = 'hello world '.join( [s]*3 ) >>> print s2 arbit hello world arbit hello world arbit