Format string with all elements of a list

前端 未结 3 441
南旧
南旧 2021-01-23 02:50
words = [\'John\', \'nice\', \'skateboarding\']
statement = \"%s you are so %s at %s\" % w for w in words

produces

File \"

        
3条回答
  •  甜味超标
    2021-01-23 03:05

    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)
      ' 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)
    

提交回复
热议问题