相关文章推荐
叛逆的长颈鹿  ·  windows opencv ...·  1 月前    · 
叛逆的长颈鹿  ·  www.diagrams.net/_mob6 ...·  8 月前    · 
叛逆的长颈鹿  ·  Basic troubleshooting ...·  10 月前    · 
叛逆的长颈鹿  ·  Integration Testing ...·  10 月前    · 
叛逆的长颈鹿  ·  Outlook Mail Merge ...·  10 月前    · 
叛逆的长颈鹿  ·  .net ...·  10 月前    · 
威武的香瓜  ·  [转]Entity Framework ...·  4 小时前    · 

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() 函数将其删除。

  •  
    推荐文章