我有一个很大的字符串,我用换行符分割了它。 如何删除所有空行(仅限空白)?
伪代码:
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']
我还尝试了正则表达式和列表解决方案,并且列出一个更快。
这是我的解决方案(根据之前的答案):
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 教程:重新模块
您可以简单地使用 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(''))
使用正向lookbehind正则表达式:
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)
输出:
""" <br>
example line 1 <br>
example line 2 <br>
example line 3 <br>
example line 4 <br>
"""
您可以组合
map
和 strip
来删除空格并使用 filter(None, iterable)
来删除空元素:
string = "a\n \n\nb"
list_of_str = string.split("\n")
list_of_str = filter(None, map(str.strip, list_of_str))
list(list_of_str)
退货:
['a', 'b']
html_content = [l for l in html_content.splitlines() if l.rstrip()]
html_content = "\n".join(html_content)
和@NullUserException说的一样,我是这样写的:
removedWhitespce = re.sub(r'^\s*$', '', line)