使用列表的所有元素格式化字符串

时间:2013-01-17 13:46:52

标签: python string list string-formatting

words = ['John', 'nice', 'skateboarding']
statement = "%s you are so %s at %s" % w for w in words

生成

File "<stdin>", line 1
statement = "%s you are so %s at %s" % w for w in words
                                           ^
SyntaxError: invalid syntax

我在这里做错了什么?假设是:len(words)==声明中的'%s'数

3 个答案:

答案 0 :(得分:6)

您还可以将新的.format样式字符串格式设置为“splat”运算符:

>>> words = ['John', 'nice', 'skateboarding']
>>> statement = "{0} you are so {1} at {2}".format(*words)
>>> print (statement)
John you are so nice at skateboarding

即使你传递了一个生成器,这也有效:

>>> statement = "{0} you are so {1} at {2}".format(*(x for x in words))
>>> print (statement)
John you are so nice at skateboarding

虽然在这种情况下,当您可以直接传递words时,无需传递生成器。

我认为非常好的一个最终形式是:

>>> statement = "{0[0]} you are so {0[1]} at {0[2]}".format(words)
>>> print statement
John you are so nice at skateboarding

答案 1 :(得分:5)

>>> statement = "%s you are so %s at %s" % tuple(words)
'John you are so nice at skateboarding'

答案 2 :(得分:2)

有两件事是错的:

  • 如果没有括号,则无法创建生成器表达式。简单地放w for w in words是python的无效语法。

  • %字符串格式化运算符需要元组,映射或单个值(不是元组或映射)作为输入。生成器不是元组,它将被视为单个值。更糟糕的是,生成器表达式不会被迭代:

    >>> '%s' % (w for w in words)
    '<generator object <genexpr> at 0x108a08730>'
    

所以以下方法可行:

statement = "%s you are so %s at %s" % tuple(w for w in words)

请注意,您的生成器表达式实际上并不会对单词进行转换或从words列表中进行选择,因此这里是多余的。所以最简单的方法就是将列表转换为tuple而不是:

statement = "%s you are so %s at %s" % tuple(words)