从Python中的给定字符串中删除奇数\n、\t\r和空格组合

2024-10-01 15:46:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个长字符串,它在单词和其他字符之间包含\n、\r\t和空格的各种组合。在

  • 我想把所有的多个空格都压缩成一个空格。在
  • 我想将所有的\n、\r\t组合减少为一个新行字符。在
  • 我希望将所有\n、\r\t和空格组合也减少为一个新行字符。在

我试过各种各样的方法都没有成功。在

  • 这里正确的Python法是什么?

  • Python3.x的解决方案会有所不同吗?

例如字符串:

ex_str = u'Word   \n \t \r   \n\n\n word2    word3   \r\r\r\r\nword4\n    word5'

所需输出[新行=\n]:

^{pr2}$

Tags: 方法字符串解决方案字符单词python3exword
3条回答

{{cd2}与

'\n'.join([' '.join(line.split()) for line in ex_str.splitlines() if line.strip()])

这将分别处理每一行,删除空行,然后将每行的所有空白压缩为单个空格。在

如果输入是一个python3字符串,那么两个Python版本都可以使用相同的解决方案。在

演示:

^{pr2}$

要保留制表符,您需要剥离并拆分空格并过滤出空字符串:

'\n'.join([' '.join([s for s in line.split(' ') if s]) for line in ex_str.splitlines() if line.strip()])

演示:

>>> '\n'.join([' '.join([s for s in line.split(' ') if s]) for line in ex_str.splitlines() if line.strip(' ')])
u'Word\n\t\nword2 word3\nword4\nword5'

使用简单正则表达式:

import re
new_str = re.sub(r'[^\S\n]+', ' ', re.sub(r'\s*[\n\t\r]\s*', '\n', ex_str))

使用正则表达式:

>>> s
u'Word   \n \t \r   \n\n\n word2    word3   \r\r\r\r\nword4\t    word5'
>>> re.sub(r'[\n\r\t ]{2,}| {2,}', lambda x: '\n' if x.group().strip(' ') else ' ', s)
u'Word\nword2 word3\nword4\nword5'
>>> 

相关问题 更多 >

    热门问题