如何删除多余的空白行

时间:2019-01-31 07:44:39

标签: python

我想删除该字符串中的所有多余空行并将其存储在其他字符串中,必须保留单个空行。

mystring1 = """This is line 1


            This is line 2
            This is line 3



            This is line 4

            This is line 5"""

所需的输出:

mystring2 = """This is line 1

            This is line 2
            This is line 3

            This is line 4

            This is line 5"""

4 个答案:

答案 0 :(得分:1)

使用re捕获两个或更多空白行:

print(re.sub("\n\n+", "\n\n", mystring1))
This is line 1

This is line 2
This is line 3

This is line 4

This is line 5

答案 1 :(得分:0)

您可以使用re并用\ n \ n替换2行或更多行:

mystring1 = """This is line 1


This is line2
This is line3



This is line4

This is line5
"""

import re
mystring2 = re.sub(r'\n{2,}', '\n\n', mystring1)

mystring2
This is line 1

This is line2
This is line3

This is line4

This is line5

答案 2 :(得分:0)

如果这是所需的输出,请使用re.sub("\n{2,}", "\n\n", mystring1)

>>> mystring1 = """This is line 1


            This is line 2
            This is line 3



            This is line 4

            This is line 5"""
>>> mystring2 = re.sub("\n{2,}", "\n\n", mystring1)
>>> print(mystring2)
This is line 1

            This is line 2
            This is line 3

            This is line 4

            This is line 5

如果要删除除换行符以外的所有多余换行符,可以像这样使用``:

>>> mystring2 = re.sub("\n+", "\n", mystring1)
>>> print(mystring2)
This is line 1
            This is line 2
            This is line 3
            This is line 4
            This is line 5

答案 3 :(得分:0)

解决方案:

import os
mystring1 = """This is line 1


            This is line 2
            This is line 3



            This is line 4

            This is line 5"""

mystring1 = os.linesep.join([s for s in mystring1.splitlines() if s])

print(mystring1)

输出:

This is line 1
This is line 2
This is line 3
This is line 4
This is line 5