[英]python - remove empty lines from end and beginning of string
I want to remove all empty lines from the beginning and the end of a string. 我想删除字符串开头和结尾的所有空行。
So the following: 因此,以下内容:
s = """
some identation here
lorem ipsum
"""
Would become: 会成为:
s = """ some identation here
lorem ipsum"""
I don't like my solutions. 我不喜欢我的解决方案。 I want something as simple and short as possible. 我想要尽可能简单和简短的内容。
Is there something built-in in python3? python3中有内置的东西吗? What are your suggestions? 您有什么建议?
You'll have to use a custom solution. 您必须使用自定义解决方案。 Split the lines by newlines, and remove empty lines from the start and end: 用换行符分隔行,并从开头和结尾删除空行:
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)
This handles the case where the 'empty' lines still contain spaces or tabs, apart from the \\n
line separators: 这可以处理“空”行仍然包含空格或制表符(除了\\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'
If there is no other whitespace than newlines, then a simple s.strip('\\n')
will do: 如果除了换行符外没有其他空格,那么一个简单的s.strip('\\n')
就可以了:
>>> '''\
...
...
...
... some indentation here
...
... lorum ipsum
...
... '''.strip('\n')
' some indentation here\n\nlorum ipsum'
s = """
some indentation here
lorem ipsum
"""
x = s.strip("\n")
print(x)
yields 产量
some indentation here
lorem ipsum
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.