141

我有:

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

我希望有:

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

用 Python 最简单的方法是什么?

4

6 回答 6

244

2021 年更新:在 Python3 中使用 f 字符串

>>> words = ['hello', 'world', 'you', 'look', 'nice']
>>> ', '.join(f'"{w}"' for w in words)
'"hello", "world", "you", "look", "nice"'

原始答案(支持 Python 2.6+)

>>> words = ['hello', 'world', 'you', 'look', 'nice']
>>> ', '.join('"{0}"'.format(w) for w in words)
'"hello", "world", "you", "look", "nice"'
于 2012-08-17T14:28:10.460 回答
64

你可以试试这个:

str(words)[1:-1]
于 2016-08-16T21:55:29.443 回答
54

您也可以执行单个format呼叫

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

更新:一些基准测试(在 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

所以看起来这format实际上是相当昂贵的

更新 2:在@JCode 的评论之后,添加一个map以确保能够join正常工作,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
于 2012-08-17T14:50:13.377 回答
7
>>> ', '.join(['"%s"' % w for w in words])
于 2012-08-17T14:30:42.427 回答
4

@jamylak 使用 F 字符串回答的更新版本(适用于 python 3.6+),我使用反引号表示用于 SQL 脚本的字符串。

keys = ['foo', 'bar' , 'omg']
', '.join(f'`{k}`' for k in keys)
# result: '`foo`, `bar`, `omg`'
于 2019-11-22T23:01:50.210 回答
0

找到更快的方法

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

在 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

结果输出是:

# "hello", "world", "you", "look", "nice"
# 'hello', 'world', 'you', 'look', 'nice'
# "hello", "world", "you", "look", "nice"
# 39.6000976562
# 166.892822266
# 220.110839844
于 2021-01-14T07:12:52.090 回答