Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.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_Python 2.7 - Fatal编程技术网

Python替换-将多个实例视为一个实例

Python替换-将多个实例视为一个实例,python,python-2.7,Python,Python 2.7,我试图用输入线命令替换所有回车。它工作正常,除非存在多个回车符。python的string.replace()函数中没有关于如何将同一项的多个实例视为一个实例的信息。这可能吗 例如,这一行: This is\nA sentence\nwith multiple\nbreaklines\n\npython. 结果应该是这样的: This is, A sentence, with multiple, breaklines, python. 但它实际上变成了这样: This is, A sente

我试图用输入线命令替换所有回车。它工作正常,除非存在多个回车符。python的string.replace()函数中没有关于如何将同一项的多个实例视为一个实例的信息。这可能吗

例如,这一行:

This is\nA sentence\nwith multiple\nbreaklines\n\npython.
结果应该是这样的:

This is, A sentence, with multiple, breaklines, python.
但它实际上变成了这样:

This is, A sentence, with multiple, breaklines, , python.
你可以使用正则表达式

In [48]: mystr = "This is\nA sentence\nwith multiple\nbreaklines\n\npython."
In [49]: re.sub(r'\n+', ', ', mystr)
Out[49]: 'This is, A sentence, with multiple, breaklines, python.'

正则表达式模式匹配一个或多个相邻的
\n
,并将它们替换为

,这将有助于识别代码中的问题以实际查看它。您始终可以手动迭代列表并替换它们。正则表达式在这里也可能有用。@Carcigenicate是正确的:使用正则表达式,将任意数量的换行符视为单个匹配项:“\n”+