【问题标题】:Best way of removing single newlines but keeping multiple newlines删除单个换行符但保留多个换行符的最佳方法
【发布时间】:2014-03-26 01:33:37
【问题描述】:

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

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

变成

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

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

【问题讨论】:

    标签: python newline


    【解决方案1】:
    >>> 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 断言来防止两边出现换行符。

    不管怎样,在野外发现了三种类型的行尾:

    1. \n 在 Linux、Mac OS X 和其他 Unices 上
    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'
    

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

    【讨论】:

    • 谢谢,这看起来很棒。但是现在我正在阅读,我认为寻找'\r\n' 甚至单身'\r' 没有多大意义。也许唯一明智的换行符是'\n''\n\r'。是对的吗?如果是这样,您能否为更简单的情况提供正则表达式?
    猜你喜欢
    • 2012-05-14
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    相关资源
    最近更新 更多