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

2024-10-01 07:43:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

因此,以下内容:

s = """


        some identation here

lorem ipsum

"""

会变成:

^{pr2}$

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

Python3里有内置的东西吗?你有什么建议?在


Tags: 字符串here结尾some解决方案内置建议python3
2条回答
s = """




  some indentation here

lorem ipsum


""" 

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

收益率

^{pr2}$

你必须使用自定义解决方案。用换行符拆分行,并从开始和结束处删除空行:

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)

这将处理除\n行分隔符之外的“空行”仍包含空格或制表符的情况:

^{pr2}$

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

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

相关问题 更多 >