首页 > 解决方案 > 删除空格并保留 \n \t .. 等

问题描述

如何从文本中保留换行符、制表符等?目前,我可以在文本文档中删除额外的空格,同时它还删除了 \n、\t、unicodes 等。

text = 'Hello world \n I wrote some random    text    here \t \n\n. I am trying      to remove extra whitespace but keep line breaks, tabs, ...etc'
text = re.sub( '\s+', ' ', text).strip()
print(text)
print(type(text))

我试过这个但没有帮助。

import textwrap
textwrap.wrap(text,80,replace_whitespace=True)

电流输出:

Hello world I wrote some random text here . I am trying to remove extra whitespace but keep line breaks, tabs, ...etc
<class 'str'>

需要的输出:

Hello world \n I wrote some random text here \t \n\n. I am trying to remove extra whitespace but keep line breaks, tabs, ...etc

标签: pythonregexpython-3.x

解决方案


您告诉正则表达式匹配所有空格,而不仅仅是空格。\s如果您只想匹配空格,请不要使用,请使用实际空格:

text = re.sub(' +', ' ', text).strip()

演示:

>>> import re
>>> text = 'Hello world \n I wrote some random    text    here \t \n\n. I am trying      to remove extra whitespace but keep line breaks, tabs, ...etc'
>>> re.sub(' +', ' ', text).strip()
'Hello world \n I wrote some random text here \t \n\n. I am trying to remove extra whitespace but keep line breaks, tabs, ...etc'

模块文档的正则表达式语法部分re,关于\s序列含义:

\s

匹配 Unicode 空白字符(包括[ \t\n\r\f\v],以及许多其他字符,例如许多语言中的排版规则要求的不间断空格)。如果使用 ASCII 标志,则仅[ \t\n\r\f\v]匹配。


推荐阅读