删除python中的额外空格

时间:2012-08-24 21:09:08

标签: 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. 

哪个不对。无论如何都可以实现上述输出。

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

'\n\n'.join(linesWithSpaces.split('\n'))

答案 2 :(得分:0)

while "\n\n" in lineWithSpaces:
    lineWithSpaces = lineWithSpaces.replace("\n\n", "\n")