在格式化字符串时多次插入相同值
我有一个这样的字符串:
s='arbit'
string='%s hello world %s hello world %s' %(s,s,s)
字符串中的所有 %s 都是相同的值(也就是 s)。有没有更好的写法?(而不是把 s 写三遍)
6 个回答
18
你可以使用字典类型的格式化:
s='arbit'
string='%(key)s hello world %(key)s hello world %(key)s' % {'key': s,}
50
incoming = 'arbit'
result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming}
你可以看看这个链接,了解一下相关内容:字符串格式化操作。
235
你可以使用高级字符串格式化,这个功能在Python 2.6和Python 3.x中都可以用:
incoming = 'arbit'
result = '{0} hello world {0} hello world {0}'.format(incoming)