Format string with all elements of a list

巧了我就是萌 提交于 2019-12-02 03:59:58

问题


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

produces

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

What am I doing wrong here? The assumption is: len(words) == number of '%s' in statement


回答1:


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



回答2:


You could also use the new .format style string formatting with the "splat" operator:

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

This works even if you pass a generator:

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

Although, in this case there is no need to pass a generator when you can pass words directly.

One final form which I think is pretty nifty is:

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



回答3:


Two things are wrong:

  • You cannot create a generator expression without parenthesis around it. Simply putting w for w in words is invalid syntax for python.

  • The % string formatting operator requires a tuple, a mapping or a single value (that is not a tuple or a mapping) as input. A generator is not a tuple, it would be seen as a single value. Even worse, the generator expression would not be iterated over:

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

So the following would work:

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

Note that your generator expression doesn't actually transform the words or make a selection from the words list, so it is redundant here. So the simplest thing is to just cast the list to a tuple instead:

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


来源:https://stackoverflow.com/questions/14380482/format-string-with-all-elements-of-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!