【发布时间】:2011-04-12 07:54:33
【问题描述】:
我有一个大字符串,我用换行符分割。 如何删除所有空行(仅限空格)?
伪代码:
for stuff in largestring:
remove stuff that is blank
【问题讨论】:
-
一个删除空行(没有空格)的衬里是this。问题标题可能会更改为“仅在 python 中删除带有空格的空行”。
我有一个大字符串,我用换行符分割。 如何删除所有空行(仅限空格)?
伪代码:
for stuff in largestring:
remove stuff that is blank
【问题讨论】:
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>
"""
【讨论】:
使用正则表达式:
re.sub(r'(?<=\n)\s+', '', s, re.MULTILINE)
当你输入时:
foo
<tab> <tab>
bar
输出将是:
foo
bar
【讨论】:
我使用此解决方案删除空行并将所有内容合并为一行:
match_p = re.sub(r'\s{2}', '', my_txt) # my_txt is text above
【讨论】:
lines = bigstring.split('\n')
lines = [line for line in lines if line.strip()]
【讨论】:
bigstring.split('\n')一起为我工作
如果你不愿意尝试正则表达式(你应该这样做),你可以使用这个:
s.replace('\n\n','\n')
重复几次以确保没有空行。或者链接命令:
s.replace('\n\n','\n').replace('\n\n','\n')
只是为了鼓励您使用正则表达式,这里有两个我觉得很直观的介绍性视频:
• Regular Expressions (Regex) Tutorial
• Python Tutorial: re Module
【讨论】:
s.replace('\n\n','\n').replace('\n\n','\n') 在 3.6 上测试。
你可以简单地使用 rstrip:
for stuff in largestring:
print(stuff.rstrip("\n")
【讨论】:
惊讶的是没有建议多行 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
>>>
【讨论】:
和@NullUserException 说的一样,我是这样写的:
removedWhitespce = re.sub(r'^\s*$', '', line)
【讨论】:
我的版本:
while '' in all_lines:
all_lines.pop(all_lines.index(''))
【讨论】:
我也尝试了正则表达式和列表解决方案,列表一个更快。
这是我的解决方案(根据以前的答案):
text = "\n".join([ll.rstrip() for ll in original_text.splitlines() if ll.strip()])
【讨论】:
【讨论】:
1000 loops, best of 3: 452 us per loop;加入、拆分和剥离:100000 loops, best of 3: 5.41 us per loop
尝试列表理解和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']
【讨论】: