python - 删除字符串结尾和开头的空行

python - remove empty lines from end and beginning of string

我想删除字符串开头和结尾的所有空行。

所以如下:

s = """


        some identation here

lorem ipsum

"""

会变成:

s = """        some identation here

lorem ipsum"""

我不喜欢我的解决方案。我想要尽可能简单和简短的东西。

python3 中有内置的东西吗?你有什么建议?

s = """




  some indentation here

lorem ipsum


""" 

x = s.strip("\n")
print(x)

产量

      some indentation here

lorem ipsum

您必须使用自定义解决方案。按换行符拆分行,并删除开头和结尾的空行:

def strip_empty_lines(s):
    lines = s.splitlines()
    while lines and not lines[0].strip():
        lines.pop(0)
    while lines and not lines[-1].strip():
        lines.pop()
    return '\n'.join(lines)

这处理 'empty' 行仍然包含空格或制表符的情况,除了 \n 行分隔符:

>>> strip_empty_lines('''\
... 
... 
... 
... 
...         some indentation here
... 
... lorem ipsum
... 
... 
... ''')
'        some indentation here\n\nlorem ipsum'
>>> strip_empty_lines('''\
... \t  \t
...     \n
...         some indentation here
... 
... lorem ipsum
... 
... ''')
'        some indentation here\n\nlorem ipsum'

如果除了换行符没有其他空格,那么一个简单的 s.strip('\n') 就可以了:

>>> '''\
... 
... 
... 
...         some indentation here
... 
... lorum ipsum
... 
... '''.strip('\n')
'        some indentation here\n\nlorum ipsum'