如何将字符串插入到具有相同多次出现的另一个字符串中

时间:2014-08-01 00:10:59

标签: python

如何简化以下语法?

three='Three'
result='One-Two-%s, One-Two-%s, One-Two-%s'%(three,three,three))

稍后编辑:

另一个惊喜:获得KeyError: 'border'

color='#262626'
style="QProgressBar{background-color: {ph:s}}".format(ph=color)

3 个答案:

答案 0 :(得分:2)

>>> three = 'Three'
>>> result = 'One-Two-{ph:s}, One-Two-{ph:s}, One-Two-{ph:s}'.format(ph=three)
>>> print result
One-Two-Three, One-Two-Three, One-Two-Three

修改

>>> style="QProgressBar{{background-color: {ph:s}}}".format(ph=color)
>>> print style
QProgressBar{background-color: #262626}

答案 1 :(得分:2)

尝试new-style formatting

您也可以使用字典扩展来执行多个变量。

three='Three'
result='One-Two-{x:}, One-Two-{x:}, One-Two-{x:}'.format(**{'x': three})

答案 2 :(得分:2)

您可以使用string formatting.在您的示例中,您可以执行此操作:

three = "Three"
result = "One-Two-{0}, One-Two-{0}, One-Two-{0}".format(three)

对于另一个问题,请将其更改为:

style="QProgressBar{{background-color: {0}}}".format(color)