相关文章推荐
愤怒的风衣  ·  Python 异步 ASGI ...·  3 月前    · 
朝气蓬勃的针织衫  ·  vue 中 ...·  3 年前    · 
爱热闹的熊猫  ·  C++面试总结 - 知乎·  3 年前    · 
冷静的脆皮肠  ·  go - Weird syntax in ...·  3 年前    · 
小眼睛的苹果  ·  Nginx 日志 ...·  3 年前    · 

python 正则表达式 删除空行

在 python 中,您可以使用正则表达式来删除空行。 您可以使用 re 模块中的 sub() 函数来执行此操作。 下面是一个示例代码:

import re
def remove_empty_lines(text):
    return re.sub(r'\n\s*\n', '\n', text)
text = "This is an example\n\n of removing\n\n empty lines."
print(remove_empty_lines(text))
# Output: "This is an example\n of removing\n empty lines."

在上面的代码中,我们定义了一个名为 remove_empty_lines 的函数,该函数使用正则表达式 r'\n\s*\n' 来搜索文本中的空行,并使用 re.sub() 函数将其删除。

  •