格式化字符串时多次插入相同的值

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)

  • 〜我个人的偏好,去找kwargs风格`result ='{st} hello world {st} hello world {st}'.format(st = incoming)` (8认同)

mha*_*wke 39

incoming = 'arbit'
result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming}
Run Code Online (Sandbox Code Playgroud)

您可能希望阅读本文以获得理解:字符串格式化操作.

  • 更好的是,你可以多次使用基本字符串:'%(s)s hello world'*3%{'s':'asdad'} (3认同)
  • @Goutham:如果您的Python版本是最新的,Adam Rosenfield的答案可能会更好。 (2认同)

Luc*_* S. 15

您可以使用字典类型的格式:

s='arbit'
string='%(key)s hello world %(key)s hello world %(key)s' % {'key': s,}
Run Code Online (Sandbox Code Playgroud)

  • mhawke:我在浏览器重新加载页面之前发布了消息,所以我不知道那个问题已经回答了问题.你不需要做个粗鲁的人!! (3认同)
  • @Lucas:我想你有可能花了13分钟输入你的答案:)并感谢你的投票...非常感谢. (2认同)

jja*_*mes 12

取决于你的意思更好.如果您的目标是删除冗余,则此方法有效.

s='foo'
string='%s bar baz %s bar baz %s bar baz' % (3*(s,))
Run Code Online (Sandbox Code Playgroud)