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

Viewed 110298

I've got:

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

I want to have:

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

What's the easiest way to do this with Python?

8 Answers

An updated version of @jamylak answer with F Strings (for python 3.6+), I've used backticks for a string used for a SQL script.

keys = ['foo', 'bar' , 'omg']
', '.join(f'`{k}`' for k in keys)
# result: '`foo`, `bar`, `omg`'

find a faster way

'"' + '","'.join(words) + '"'

test in Python 2.7:

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

    print '"' + '","'.join(words) + '"'
    print str(words)[1:-1]
    print '"{0}"'.format('", "'.join(words))

    t = time() * 1000
    range10000 = range(100000)

    for i in range10000:
        '"' + '","'.join(words) + '"'

    print time() * 1000 - t
    t = time() * 1000

    for i in range10000:
        str(words)[1:-1]
    print time() * 1000 - t

    for i in range10000:
        '"{0}"'.format('", "'.join(words))

    print time() * 1000 - t

The resulting output is:

# "hello", "world", "you", "look", "nice"
# 'hello', 'world', 'you', 'look', 'nice'
# "hello", "world", "you", "look", "nice"
# 39.6000976562
# 166.892822266
# 220.110839844
words = ['hello', 'world', 'you', 'look', 'nice']
S = ""
for _ in range(len(words)-1):
    S+=f'"{words[_]}"'+', '
S +=f'"{words[len(words)-1]}"'
print("'"+S+"'")

OUTPUT:

'"hello", "world", "you", "look", "nice"'
# Python3 without for loop
conc_str = "'{}'".format("','".join(['a', 'b', 'c']))
print(conc_str) 

# "'a', 'b', 'c'"
Related