-5

I want to turn this list:

['1','2','3','4']

into this string:

"%(1)s, %(2)s, %(3)s, %(4)s"

How can I do this, preferrably in ONE LINE?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Sahand
  • 7,980
  • 23
  • 69
  • 137

1 Answers1

5

Using string formatting, str.join() and a list comprehension:

', '.join(['%({})s'.format(i) for i in inputlist])

Demo:

>>> inputlist = ['1','2','3','4']
>>> ', '.join(['%({})s'.format(i) for i in inputlist])
'%(1)s, %(2)s, %(3)s, %(4)s'

See List comprehension without [ ] in Python why it is better to use a list comprehension, and not a generator expression here.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    `join` can take a generator. No need to first create a `list`. – too honest for this site Sep 26 '15 at 13:43
  • The `str.join()` method turns the generator into a list, because it has to parse the contents twice (to compute the length, then to produce the output). By using a list comprehension you gain a little performance. See [list comprehension without \[ \], Python](http://stackoverflow.com/a/9061024) – Martijn Pieters Sep 26 '15 at 13:46
  • Interesting. Thanks (although I still prefer without the comprehension, if speed is not a matter. It is just more clear - but I will definitively keep that in mind, not only for `join`). I wonder if this changes with list contents. – too honest for this site Sep 26 '15 at 13:57
  • @Olaf: it is *specific to `str.join()` that the list comprehension is faster; it doesn't change with the contents, it is the performance difference between a list comprehension and a generator plus having to convert the latter to a list *anyway* that makes the difference here. – Martijn Pieters Sep 26 '15 at 14:12