gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:13:53 25 4
gpt4 key购买 nike

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

  • 我想将所有多个空格缩减为一个空格。
  • 我想将所有\n、\r、\t 组合缩减为单个换行符。
  • 我想将所有\n、\r、\t 和空格组合也减少为单个换行符。

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

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

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

例。字符串:

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

期望的输出 [new new-line =\n]:

new_str = u'Word\nword2 word3\nword4\nword5'

最佳答案

结合使用 str.splitlines() 并使用 str.split() 拆分所有空白:

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

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

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

演示:

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

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

'\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'

关于python - 从 Python 中的给定字符串中删除奇数\n、\t、\r 和空格组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17809119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com