[英]Python: How to remove empty quotes and a new line from the beginning of the string?
[英]python - remove empty lines from end and beginning of string
我想删除字符串开头和结尾的所有空行。
因此,以下内容:
s = """
some identation here
lorem ipsum
"""
会成为:
s = """ some identation here
lorem ipsum"""
我不喜欢我的解决方案。 我想要尽可能简单和简短的内容。
python3中有内置的东西吗? 您有什么建议?
您必须使用自定义解决方案。 用换行符分隔行,并从开头和结尾删除空行:
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
行分隔符)的情况:
>>> 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'
s = """
some indentation here
lorem ipsum
"""
x = s.strip("\n")
print(x)
产量
some indentation here
lorem ipsum
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.