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

kad*_*ian 2 python string list string-formatting

words = ['John', 'nice', 'skateboarding']
statement = "%s you are so %s at %s" % w for w in words
Run Code Online (Sandbox Code Playgroud)

产生

File "<stdin>", line 1
statement = "%s you are so %s at %s" % w for w in words
                                           ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

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

mgi*_*son 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
Run Code Online (Sandbox Code Playgroud)

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

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

虽然,在这种情况下,当你可以words直接通过时,不需要传递发生器.

我认为非常好的最后一种形式是:

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


Ale*_*yev 5

>>> statement = "%s you are so %s at %s" % tuple(words)
'John you are so nice at skateboarding'
Run Code Online (Sandbox Code Playgroud)