簡體   English   中英

如何在Python中刪除帶有或不帶有空格的空行

[英]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']

使用正則表達式:

if re.match(r'^\s*$', line):
    # line is empty (has only the following: \t\n\r and whitespace)

使用正則表達式 + filter()

filtered = filter(lambda x: not re.match(r'^\s*$', x), original)

正如在鍵盤上看到的那樣。

我還嘗試了 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM