Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
任意数量的字符串,python_Python - Fatal编程技术网

任意数量的字符串,python

任意数量的字符串,python,python,Python,假设我们有一个列表,其元素是字符串项。例如,x=['dogs','cats'] 如何为列表x中任意数量的项目创建一个新字符串“dogs”,“cats” 使用str.join和repr: >>> x = ['dogs', 'cats'] >>> ", ".join(map(repr,x)) "'dogs', 'cats'" 或: 我将使用以下方法: ', '.join(repr(s) for s in x) 对于这种特殊情况,这比“,”快约17倍。join(

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


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

使用
str.join
repr

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


我将使用以下方法:

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

对于这种特殊情况,这比
“,”快约17倍。join()


您将如何处理包含
字符的项目?特别是:您是否愿意像Python的
repr
函数那样处理它们(基本上,这意味着如果足够,则用双引号替换外部引号,如果不足够,则用反斜杠转义引号替换),或者您想要不同的规则?谢谢,这对我有用。仍在试图找出repr和str之间的区别。
', '.join(repr(s) for s in x)
>>> x = "['dogs', 'cats']"
>>> repr(x)[1:-1]
"'dogs', 'cats'"