使用单个变量格式化多个%s

时间:2016-11-10 00:31:00

标签: python string-formatting

我有一个未知数量为%s的字符串,需要使用单个字符串进行格式化。

例如,如果我有字符串"%s some %s words %s"并希望使用单词house对其进行格式化,则应输出"house some house words house"

执行以下操作会给我一个错误:

>>> "%s some %s words %s" % ("house")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string

所以,我决定做以下工作,这对于这样一个简单的问题似乎过于复杂。

var = "house"
tup = (var,)
while True:
    try:
        print "%s some %s words %s" % tup
        break
    except:
        tup += (var,)

有更多的pythonic方式吗?

3 个答案:

答案 0 :(得分:4)

如果您确定知道自己正在修改%s,可以这样做:

var = "house"
tup = (var,)
txt = "%s some %s words %s"

print txt % (tup * txt.count("%s"))

但更好的解决方案是使用str.format()使用不同的语法,但允许您按编号指定项目,以便您可以重复使用它们:

var = "house"
txt = "{0} some {0} words {0}"

print txt.format(var)

答案 1 :(得分:4)

以下是一些选项:

格式字符串(和Formatter类)

使用str.format是最pythonic的方式,阅读起来非常简单。这两种风格都很受欢迎:

位置参数

'{0} some {0} words {0}'.format('house')

命名参数

'{word} some {word} words {word}'.format(word='house')

在评论中,您提到由于其他遗留代码而保留原始格式字符串。你可以像这样破解:

'%s some %s words %s'.replace('%s', '{0}').format('house')

(我不推荐它,但你可以&#34;短路&#34;这个想法通过在替换调用而不是'house'中使用'{0}'。)

那就是说,我真的认为首先更改模板字符串是一个更好的主意。

模板字符串

在浏览string文档后,会想到另一个替代方案:较早的string.Template类。默认情况下,它会替换基于$的值,但您可以将其子类化为覆盖分隔符。例如:

class MyTemplate(Template):
    """
    Overriding default to maintain compatibility with legacy code.
    """
    delimiter = '%'


t = MyTemplate('%s some %s words %s')
t.substitute(s='house')

请记住,这种情况不常见,但您可以编写一次并在每次使用此类字符串时重复使用它(假设只有一个输入值被替换)。写一次至少是Pythonic!

文字字符串插值

在Python 3.6中,Ruby-style string interpolation是社区尚未就此达成共识的另一种选择。例如:

s = 'house'
f'{s} some {s} words {s}'

答案 2 :(得分:1)

为什么不使用format

"{0} some {0} words {0}".format("house")