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

Ric*_*aez 4 python newline

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

如在

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

转变为

"foo\n\nbar one two three\n\n\nhello"

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

Joh*_*ica 5

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

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

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

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

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

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

当然,|\r如果您不关心 Mac 行结尾,请去掉它,这种情况很少见。