我有:
words = ['hello', 'world', 'you', 'look', 'nice']
我希望:
'"hello", "world", "you", "look", "nice"'
用Python做最简单的方法是什么?
答案 0 :(得分:122)
>>> words = ['hello', 'world', 'you', 'look', 'nice']
>>> ', '.join('"{0}"'.format(w) for w in words)
'"hello", "world", "you", "look", "nice"'
答案 1 :(得分:42)
您也可以执行一次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
答案 2 :(得分:20)
你可以试试这个:
str(words)[1:-1]
答案 3 :(得分:7)
>>> ', '.join(['"%s"' % w for w in words])
答案 4 :(得分:0)
@jamylak答案的更新版本,带有F字符串(适用于python 3.6+),我使用反引号表示用于SQL脚本的字符串。
na.omit(A, cols="right_date")