我想从字符串的开头和结尾删除所有空行。
以下内容:
s = """
some identation here
lorem ipsum
"""
会变成:
s = """ some identation here
lorem ipsum"""
我不喜欢我的解决方案。我想要尽可能简单和短暂的东西。
python3中是否有内置内容?你有什么建议?
答案 0 :(得分:4)
您必须使用自定义解决方案。按换行分割线条,并从开头和结尾删除空行:
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'
答案 1 :(得分:1)
L.latlng
产量
s = """
some indentation here
lorem ipsum
"""
x = s.strip("\n")
print(x)