gpt4 book ai didi

python - 删除单个换行符但保留多个换行符的最佳方法

转载 作者:太空宇宙 更新时间:2023-11-04 01:18:48 24 4
gpt4 key购买 nike

从字符串中删除单个换行符但保留多个换行符的最 pythonic 方法是什么?

如在

"foo\n\nbar\none\n\rtwo\rthree\n\n\nhello"

变成

"foo\n\nbar 一二三\n\n\n你好"

我正在考虑使用 splitlines(),然后用 "\n" 替换空行,然后再次将所有内容连接起来,但我怀疑有更好/更简单的方法。也许使用正则表达式?

最佳答案

>>> re.sub('(?<![\r\n])(\r?\n|\n?\r)(?![\r\n])', ' ', s)
'foo\n\nbar one two three\n\n\nhello'

这会寻找 \r?\n\n?\r并使用 lookbehind 和 lookahead 断言来防止两边出现换行符。

就其值(value)而言,在野外发现了三种类型的行尾:

  1. \n在 Linux、Mac OS X 和其他 Unices 上
  2. \r\n在 Windows 上,在 HTTP 协议(protocol)中
  3. \r在 Mac OS 9 及更早版本上

前两个是迄今为止最常见的。如果你想将可能性限制在这三个,你可以这样做:

>>> re.sub('(?<![\r\n])(\r?\n|\r)(?![\r\n])', ' ', s)
'foo\n\nbar one two three\n\n\nhello'

当然,去掉 |\r如果您不关心很少见的 Mac 行结尾。

关于python - 删除单个换行符但保留多个换行符的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22649851/

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