Gou*_*ham 101 python string format
我有一个这种形式的字符串
s='arbit'
string='%s hello world %s hello world %s' %(s,s,s)
Run Code Online (Sandbox Code Playgroud)
字符串中的所有%s都具有相同的值(即s).有没有更好的写作方式?(而不是列出s三次)
Ada*_*eld 190
您可以使用Python 2.6和Python 3.x中提供的高级字符串格式:
incoming = 'arbit'
result = '{0} hello world {0} hello world {0}'.format(incoming)
Run Code Online (Sandbox Code Playgroud)
mha*_*wke 39
incoming = 'arbit'
result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming}
Run Code Online (Sandbox Code Playgroud)
您可能希望阅读本文以获得理解:字符串格式化操作.
Luc*_* S. 15
您可以使用字典类型的格式:
s='arbit'
string='%(key)s hello world %(key)s hello world %(key)s' % {'key': s,}
Run Code Online (Sandbox Code Playgroud)
jja*_*mes 12
取决于你的意思更好.如果您的目标是删除冗余,则此方法有效.
s='foo'
string='%s bar baz %s bar baz %s bar baz' % (3*(s,))
Run Code Online (Sandbox Code Playgroud)