Append a list of strings in python and wrap each string in quotation marks

I have:

words = ['hello', 'world', 'you', 'look', 'nice'] 

I want to have:

 '"hello", "world", "you", "look", "nice"' 

What is the easiest way to do this using Python?

+44
python string list join
Aug 17 2018-12-12T00:
source share
4 answers
 >>> words = ['hello', 'world', 'you', 'look', 'nice'] >>> ', '.join('"{0}"'.format(w) for w in words) '"hello", "world", "you", "look", "nice"' 
+71
Aug 17 2018-12-12T00:
source share

you can also make one call to format

 >>> words = ['hello', 'world', 'you', 'look', 'nice'] >>> '"{0}"'.format('", "'.join(words)) '"hello", "world", "you", "look", "nice"' 

Update: some benchmarking (running on 2009 mbp):

 >>> timeit.Timer("""words = ['hello', 'world', 'you', 'look', 'nice'] * 100; ', '.join('"{0}"'.format(w) for w in words)""").timeit(1000) 0.32559704780578613 >>> timeit.Timer("""words = ['hello', 'world', 'you', 'look', 'nice'] * 100; '"{}"'.format('", "'.join(words))""").timeit(1000) 0.018904924392700195 

So it seems that format is actually quite expensive

Update 2: after @JCode's comment, adding map to ensure that join will work, Python 2.7.12

 >>> timeit.Timer("""words = ['hello', 'world', 'you', 'look', 'nice'] * 100; ', '.join('"{0}"'.format(w) for w in words)""").timeit(1000) 0.08646488189697266 >>> timeit.Timer("""words = ['hello', 'world', 'you', 'look', 'nice'] * 100; '"{}"'.format('", "'.join(map(str, words)))""").timeit(1000) 0.04855608940124512 >>> timeit.Timer("""words = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] * 100; ', '.join('"{0}"'.format(w) for w in words)""").timeit(1000) 0.17348504066467285 >>> timeit.Timer("""words = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] * 100; '"{}"'.format('", "'.join(map(str, words)))""").timeit(1000) 0.06372308731079102 
+32
Aug 17 '12 at 14:50
source share

You can try the following:

 str(words)[1:-1] 
+9
Aug 16 '16 at 21:55
source share
 >>> ', '.join(['"%s"' % w for w in words]) 
+7
Aug 17 '12 at 14:30
source share



All Articles