如何在python中从多行字符串中删除特定的空行?

如何在python中从多行字符串中删除特定的空行?,python,Python,我正在使用模板创建多个.txt文件。某些文件将具有空值,因此我要删除生成的空行: arg1 = '- this is the third line' arg2 = '- this is the fourth line' arg3 = '' arg4 = '- this is the sixth line' 应用于模板时,结果为以下内容: (内容为多行字符串) 从模板中: This is the first line: $arg1 $arg2 $arg3 $ar

我正在使用模板创建多个.txt文件。某些文件将具有空值,因此我要删除生成的空行:

arg1 = '- this is the third line'
arg2 = '- this is the fourth line'
arg3 = ''
arg4 = '- this is the sixth line'
应用于模板时,结果为以下内容:

(内容为多行字符串)

从模板中:

This is the first line:

    $arg1
    $arg2
    $arg3
    $arg4

This is some other content whose possible empty lines need to be left alone.
因此,在我将此内容写入文件之前,我想删除那些难看的空行,因此看起来如下所示:

This is the first line:

        - this is the third line
        - this is the fourth line         
        - this is the sixth line

This is some other content whose possible empty lines need to be left alone.
for line, index_line in zip(content.splitlines(), range(1, 11)):
    if index_line in range(4, 11) and line == '    ':
        # command that will remove the empty line and save the new content
换句话说,我想删除特定行范围内的所有空行,如下所示:

This is the first line:

        - this is the third line
        - this is the fourth line         
        - this is the sixth line

This is some other content whose possible empty lines need to be left alone.
for line, index_line in zip(content.splitlines(), range(1, 11)):
    if index_line in range(4, 11) and line == '    ':
        # command that will remove the empty line and save the new content
另外,范围是不同的,因为这是我自己的代码片段,但给定示例的范围是:

范围(1,7)
#当我们通过第六行时停止


range(3,7)
#只检查给定范围内的行

您需要的函数是
list.pop(index)


如果范围可能不同,并且我们可以使用“^-\s”作为开始和停止删除空行的标志,那么您可以使用正则表达式

import re

s = '''This is the first line:

    - this is the third line
    - this is the fourth line

    - this is the sixth line


This is some other content whose possible empty lines need to be left alone.

Leave that last line alone.
'''

remove_empty = False
lines = []
for line in s.splitlines():
    l = line.strip()
    if l != '':
        dashed = (re.match('^-\s', l) is not None)
        if dashed and not remove_empty:
            # Now we need to start removing empty strings
            remove_empty = (re.match('^-\s', l) is not None)
        elif not dashed and remove_empty:
            # Now it is time to stop
            remove_empty = False
            lines.append('')

    if l != '' or not remove_empty:
        lines.append(line)

print '\n'.join(lines)
# This is the first line:
#
#     - this is the third line
#     - this is the fourth line
#     - this is the sixth line
#
# This is some other content whose possible empty lines need to be left alone.
#
# Leave that last line alone.

如果您确实知道范围,那么Aaron D可能会有更好的解决方案。

如果要删除多个连续行,则以前的版本将不起作用,因为
pop()
会更改列表的结构,从而跳过对下一项的比较。保存索引并按相反顺序删除可以避免这种情况。