python - 正则表达式 Python - 用单个空格替换换行符、制表符、空格的任意组合
问题描述
我正在尝试找到一个常规 exp,它使我能够用一个空格替换所有换行符和制表符(\n、\r、\t 等),以及之前、之后和中间的任何空格。例如,字符串
'版权所有 ©\n\t\t\t\n\t\t\t2019\n\t\t\tApple Inc. 保留所有权利。'
应该变成
“版权所有 © 2019 Apple Inc. 保留所有权利。”
此外,如果原始字符串是:
'版权 © \n\t \t\t\n \t\t\t2019\n\t\t\t Apple Inc. 保留所有权利。'
最后的结果应该是一样的。
对于单个换行符,在没有额外空格的最简单情况下,它会类似于
re.sub(r"\n", " ", html)
但由于我不经常处理正则表达式,我不知道如何解决我所追求的。
解决方案
尝试使用匹配所有空白字符的 \s。
>>> import re
>>> s = 'Copyright ©\n\t\t\t\n\t\t\t2019\n\t\t\tApple Inc. All rights reserved.'
>>> s = re.sub("\s+", " ", s)
>>> s
'Copyright © 2019 Apple Inc. All rights reserved.'
推荐阅读
- c++ - 使用 FFmpeg 初始化 mkv 的输出文件
- php - 在值中包含换行符
- javascript - 递减计数器有奇怪的行为
- php - 如何在 PHP 中获取一年中某一天的日期?
- r - 绘制 r 中的条件分布
- angular - 如何以角度反应形式清除 FormArray 值?
- java - 运行带有 txt 测试用例条目的 .py 并将输出重定向到另一个 .txt
- flutter - _$CustomClass 显示“返回类型“Type”不是“CustomClass”的错误,由匿名闭包定义。`
- javascript -
我应该使用
<a href="url">Something/>
因此,当我单击它时,它会将我重定向到我的 URL。
但现在我想对 onClick 方法做同样的事情(使用我的路由器)。
在我的代码中,我尝试使用它:
- java - 如何在 RSA 中进行密钥交换以进行解密