2
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”的数量

4

3 回答 3

6

您还可以使用带有“splat”运算符的新.format样式字符串格式:

>>> 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
于 2013-01-17T14:06:48.787 回答
5
>>> statement = "%s you are so %s at %s" % tuple(words)
'John you are so nice at skateboarding'
于 2013-01-17T13:48:19.467 回答
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列表中进行选择,因此这里是多余的。所以最简单的事情就是将列表转换为 a tuple

statement = "%s you are so %s at %s" % tuple(words)
于 2013-01-17T13:51:51.883 回答