2

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

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

4

3 回答 3

3

使用str.joinrepr

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

或者:

>>> ", ".join([repr(y) for y in x])
"'dogs', 'cats'"
于 2013-06-18T20:56:07.663 回答
2

我会使用以下内容:

', '.join(repr(s) for s in x)
于 2013-06-18T20:57:07.453 回答
1

对于这种特殊情况,这比大约快 17 倍", ".join()

>>> x = "['dogs', 'cats']"
>>> repr(x)[1:-1]
"'dogs', 'cats'"
于 2013-06-18T21:01:21.343 回答