[英]How to remove empty lines with or without whitespace in Python
我有大字符串,我用换行符分割。 如何删除所有空行(仅限空格)?
伪代码:
for stuff in largestring:
remove stuff that is blank
尝试列表理解和string.strip()
:
>>> mystr = "L1\nL2\n\nL3\nL4\n \n\nL5"
>>> mystr.split('\n')
['L1', 'L2', '', 'L3', 'L4', ' ', '', 'L5']
>>> [line for line in mystr.split('\n') if line.strip() != '']
['L1', 'L2', 'L3', 'L4', 'L5']
我还尝试了 regexp 和 list 解决方案,并且list one is fast 。
这是我的解决方案(根据以前的答案):
text = "\n".join([ll.rstrip() for ll in original_text.splitlines() if ll.strip()])
lines = bigstring.split('\n')
lines = [line for line in lines if line.strip()]
惊讶的是没有建议多行 re.sub(哦,因为你已经拆分了你的字符串......但为什么呢?):
>>> import re
>>> a = "Foo\n \nBar\nBaz\n\n Garply\n \n"
>>> print a
Foo
Bar
Baz
Garply
>>> print(re.sub(r'\n\s*\n','\n',a,re.MULTILINE))
Foo
Bar
Baz
Garply
>>>
如果你不愿意尝试正则表达式(你应该这样做),你可以使用这个:
s.replace('\n\n','\n')
重复几次以确保没有空行。 或者链接命令:
s.replace('\n\n','\n').replace('\n\n','\n')
为了鼓励您使用正则表达式,这里有两个我觉得很直观的介绍视频:
•正则表达式 (Regex) 教程
• Python 教程:re 模块
你可以简单地使用 rstrip:
for stuff in largestring:
print(stuff.rstrip("\n")
我使用此解决方案删除空行并将所有内容合并为一行:
match_p = re.sub(r'\s{2}', '', my_txt) # my_txt is text above
我的版本:
while '' in all_lines:
all_lines.pop(all_lines.index(''))
在科莫多编辑中按Ctrl + H星标记(视为正则表达式),单击上面的链接查看快照。
我到目前为止找到的最简单的解决方案是 -
for stuff in largestring:
if stuff.strip():
print(stuff)
使用正向后视正则表达式:
re.sub(r'(?<=\n)\s+', '', s, re.MULTILINE)
当你输入:
foo
<tab> <tab>
bar
输出将是:
foo
bar
str_whith_space = """
example line 1
example line 2
example line 3
example line 4"""
new_str = '\n'.join(el.strip() for el in str_whith_space.split('\n') if el.strip())
print(new_str)
"""
示例第 1 行
示例第 2 行
示例第 3 行
示例第 4 行
"""
与@NullUserException 所说的相同,我是这样写的:
removedWhitespce = re.sub(r'^\s*$', '', line)
while True:
try:
all_lines.remove('')
except ValueError:
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.