任意数量的字符串字符串,python

时间:2013-06-18 20:55:07

标签: python

假设我们有一个列表,其元素是字符串项。例如,x = ['dogs', 'cats']

如何为列表x中的任意数量的项目创建新字符串"'dogs', 'cats'"

3 个答案:

答案 0 :(得分:3)

使用str.joinrepr

>>> x = ['dogs', 'cats']
>>> ", ".join(map(repr,x))
"'dogs', 'cats'"

或:

>>> ", ".join([repr(y) for y in x])
"'dogs', 'cats'"

答案 1 :(得分:2)

我会使用以下内容:

', '.join(repr(s) for s in x)

答案 2 :(得分:1)

对于这种特殊情况,这比", ".join()

快约17倍
>>> x = "['dogs', 'cats']"
>>> repr(x)[1:-1]
"'dogs', 'cats'"