需要加入列表的元素,但加入后保留元素周围的 '' [英] Need to join the elements of a list but keep the '' around element after joining
本文介绍了需要加入列表的元素,但加入后保留元素周围的 ''的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的清单是:
example = ['a', 'b', 'c']
如果我使用 ",".join(example)
,删除元素周围的 ' '
.
我希望我的输出是:
example = "'a','b','c'"
有什么优雅的方法吗?
解决方案
不确定它是否优雅,但它有效(基于 list
对象的默认表示,因此根本不灵活):
另一个(易于定制):
<预><代码>>>>示例 = ['a', 'b', 'c']>>>"'{joined}'".format(joined="', '".join(example))'a','b','c'"其他人已经提出了类似的建议,但仍然:
<预><代码>>>>示例 = ['a', 'b', 'c']>>>', '.join([repr(x) for x in example])'a','b','c'"my list is:
example = ['a', 'b', 'c']
If I use ",".join(example)
, removes ' '
around the elements.
I want my output to be:
example = "'a','b','c'"
Any elegant way to do it?
解决方案
Not sure if it's elegant, but it works (based on the default representation of list
objects and therefore not flexible at all):
>>> example = ['a', 'b', 'c']
>>> repr(example)[1:-1] # [1:-1] to remove brackets
"'a', 'b', 'c'"
Another one (easily customizable):
>>> example = ['a', 'b', 'c']
>>> "'{joined}'".format(joined="', '".join(example))
"'a', 'b', 'c'"
Something like this was already suggested by others, but still:
>>> example = ['a', 'b', 'c']
>>> ', '.join([repr(x) for x in example])
"'a', 'b', 'c'"
这篇关于需要加入列表的元素,但加入后保留元素周围的 ''的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文