【发布时间】:2012-08-14 00:20:06
【问题描述】:
我有:
words = ['hello', 'world', 'you', 'look', 'nice']
我想拥有:
'"hello", "world", "you", "look", "nice"'
用 Python 最简单的方法是什么?
【问题讨论】:
我有:
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"'
【讨论】:
repr 在这种特定情况下这是一个小技巧,而不是用引号明确
找到更快的方法
'"' + '","'.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
【讨论】:
@jamylak 使用 F 字符串回答的更新版本(适用于 python 3.6+),我对用于 SQL 脚本的字符串使用了反引号。
keys = ['foo', 'bar' , 'omg']
', '.join(f'`{k}`' for k in keys)
# result: '`foo`, `bar`, `omg`'
【讨论】:
f 字符串似乎是现在最好的方式
您也可以执行单个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(words) 替换为 .join(map(str, words)) 并向我们展示这是怎么回事。
你可以试试这个:
str(words)[1:-1]
【讨论】:
>>> ', '.join(['"%s"' % w for w in words])
【讨论】: