Python 正则表达式过滤多余换行符
使用 Python 的 re.sub 函数和正则表达式,可以有效地过滤文本中的多余换行符,使文本格式更简洁。
代码示例:
import re
text = '''
This is some text.
This is another line.
This is the last line.
'''
filtered_text = re.sub(r'\n+', '\n', text)
print(filtered_text)
输出结果:
This is some text.
This is another line.
This is the last line.
解释:
- 正则表达式
\n+匹配一个或多个连续的换行符\n。 re.sub函数将匹配到的连续换行符替换为一个换行符\n,从而过滤掉多余的换行。
通过这种方法,我们可以轻松地将文本中的多余换行符去除,使文本格式更美观、更易读。
原文地址: https://www.cveoy.top/t/topic/bQF7 著作权归作者所有。请勿转载和采集!