Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format string with all elements of a list

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

like image 515
kadrian Avatar asked Jan 30 '26 18:01

kadrian


1 Answers

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
like image 180
mgilson Avatar answered Feb 02 '26 06:02

mgilson