我有:
words = ['hello', 'world', 'you', 'look', 'nice']
我希望有:
'"hello", "world", "you", "look", "nice"'
用 Python 最简单的方法是什么?
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"'
你可以试试这个:
str(words)[1:-1]
您也可以执行单个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
>>> ', '.join(['"%s"' % w for w in words])
@jamylak 使用 F 字符串回答的更新版本(适用于 python 3.6+),我使用反引号表示用于 SQL 脚本的字符串。
keys = ['foo', 'bar' , 'omg']
', '.join(f'`{k}`' for k in keys)
# result: '`foo`, `bar`, `omg`'
找到更快的方法
'"' + '","'.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