我的清单是:
example = ['a', 'b', 'c']
如果我使用",".join(example)
,请删除元素周围的' '
。
我希望我的输出为:
example = "'a','b','c'"
任何优雅的方式吗?
答案 0 :(得分:4)
不确定它是否优雅,但它有效(基于list
个对象的默认表示,因此根本不灵活):
>>> example = ['a', 'b', 'c']
>>> repr(example)[1:-1] # [1:-1] to remove brackets
"'a', 'b', 'c'"
另一个(可轻松定制):
>>> example = ['a', 'b', 'c']
>>> "'{joined}'".format(joined="', '".join(example))
"'a', 'b', 'c'"
其他人已经提出过这样的建议,但仍然是:
>>> example = ['a', 'b', 'c']
>>> ', '.join([repr(x) for x in example])
"'a', 'b', 'c'"
答案 1 :(得分:3)
','.join(map(repr,example))
Out[74]: "'a','b','c'"
答案 2 :(得分:2)
只是几个时间:
>>> import timeit
>>> setup = 'example = list("abcdefghijklmnop")'
>>> timeit.timeit(setup=setup, stmt = '",".join(repr(item) for item in example)')
4.316254299507404
>>> timeit.timeit(setup=setup, stmt = '",".join([repr(item) for item in example])')
3.393636402412758
>>> timeit.timeit(setup=setup, stmt = '",".join(map(repr, example))')
3.2305143115811887
>>> timeit.timeit(setup=setup, stmt = '''"'{joined}'".format(joined="','".join(example))''')
1.308451301197806