Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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_String - Fatal编程技术网

删除python中多余的空格

删除python中多余的空格,python,string,Python,String,我有一个文件,上面写着: o hi! My name is Saurabh. o I like python. 我想要像这样的东西: o hi! My name is Saurabh. o I like python. 我试着说: removedSpaces=' '.join(lineWithSpaces.split()) 看起来它删除了所有的空格 它给了我 o hi! My name is Saurabh.o I like python. 这是不正确的。无论如何,是否有可能

我有一个文件,上面写着:

o hi! My name is Saurabh.




o I like python.
我想要像这样的东西:

o hi! My name is Saurabh.

o I like python.
我试着说:

removedSpaces=' '.join(lineWithSpaces.split())
看起来它删除了所有的空格

它给了我

o hi! My name is Saurabh.o I like python. 
这是不正确的。无论如何,是否有可能实现上述输出

import re
removedSpaces = re.sub(r'\n{3,}', "\n\n", lineWithSpaces)

这会将三个或更多新行的所有运行转换为两个新行

不完全正确;这将用两条换行符替换所有空格。您想要拆分('\n')@nneonneo,Santa:不。没有修复。现在字符串中的每一个换行符都将替换为两个换行符:
'\n\n.join(“a\n\nb.split(“\n”))
给出
'a\n\n\nb'
。它在处理数字和\n之后工作。非常感谢--索拉布
'\n\n'.join(linesWithSpaces.split('\n'))
while "\n\n" in lineWithSpaces:
    lineWithSpaces = lineWithSpaces.replace("\n\n", "\n")