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



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

  • 我想将所有多个空格减少为一个空格
  • 我想将所有的\n,\r,\t组合符减少为一个换行符
  • 我还想将所有的\n、\r、\t和空格组合减少为一个换行符

我用各种方法尝试过''.join(str.split()),但都没有成功。

  • 这里正确的Python方式是什么?

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

Ex。字符串:

ex_str = u'Word   n t r   nnn word2    word3   rrrrnword4n    word5'

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

new_str = u'Wordnword2 word3nword4nword5'

使用str.splitlines()组合并使用str.split():对所有空白进行拆分

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

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

如果输入是Python3字符串,则相同的解决方案适用于两个Python版本。

演示:

>>> ex_str = u'Word   n t r   nnn word2    word3   rrrrnword4n    word5'
>>> 'n'.join([' '.join(line.split()) for line in ex_str.splitlines() if line.strip(' ')])
u'Wordnword2 word3nword4nword5'

为了保留选项卡,您需要剥离上的空格并过滤掉空字符串:

'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'Wordntnword2 word3nword4nword5'

使用简单的regexps:

import re
new_str = re.sub(r'[^Sn]+', ' ', re.sub(r's*[ntr]s*', 'n', ex_str))

使用正则表达式:

>>> s
u'Word   n t r   nnn word2    word3   rrrrnword4t    word5'
>>> re.sub(r'[nrt ]{2,}| {2,}', lambda x: 'n' if x.group().strip(' ') else ' ', s)
u'Wordnword2 word3nword4nword5'
>>> 

另一个使用regex的解决方案,它用空格u'word1ttword2'替换制表符,或者您真的想在这里添加换行符吗?

import re
new_str = re.sub(r"[n ]{2,}", "n", re.sub(r"[tr ]+", " ", ex_str))
'n'.join(str.split())

输出:

u'Wordnword2nword3nword4nword5'

最新更新