joinpython中的string列表,并用引号将每个string换行
我有:
words = ['hello', 'world', 'you', 'look', 'nice']
我希望有:
'"hello", "world", "you", "look", "nice"'
用Python做这个最简单的方法是什么?
>>> words = ['hello', 'world', 'you', 'look', 'nice'] >>> ', '.join('"{0}"'.format(w) for w in words) '"hello", "world", "you", "look", "nice"'
你也可以执行一个format
调用
>>> words = ['hello', 'world', 'you', 'look', 'nice'] >>> '"{0}"'.format('", "'.join(words)) '"hello", "world", "you", "look", "nice"'
更新:一些基准(在2009年执行):
>>> 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
你可以试试这个:
str(words)[1:-1]
>>> ', '.join(['"%s"' % w for w in words])