python - 删除空格并保留 \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
解决方案
您告诉正则表达式匹配所有空格,而不仅仅是空格。\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]
匹配。
推荐阅读
- powershell - 如何在 Windows Server Core 中设置默认 Powershell 版本
- pandas - 如何根据熊猫的范围进行匹配
- php - Stripe Prebuilt Checkout Session 在 Laravel 8 中返回 404 错误
- python - 是否可以在单行上使用 pandas.replace 函数?
- python - 按随机生成的权重对元组进行排序
- azure - 如何使用 azure 数据工厂将数据从 azure SQL 数据库增量存储到 azure blob 存储,基于某些条件:需要更新日期
- javascript - 我无法获得我想要的对象值
- php - php如何合并2个多维数组?
- android - android Core Splashscreen API 在黑暗模式下使启动器图标变黑
- .net - MVC Kendo Grid DataTable DataSource Format by Field Type