python中是否有字符串折叠库函数?

Evg*_*eny 4 python string line-breaks

是否有跨平台库函数将多行字符串折叠为单行字符串而没有重复空格?

我在下面提出了一些剪辑,但我想知道是否有一个我可以导入的标准函数,甚至可能在C中进行了优化?

def collapse(input):
    import re
    rn = re.compile(r'(\r\n)+')
    r = re.compile(r'\r+')
    n = re.compile(r'\n+')
    s = re.compile(r'\ +')
    return s.sub(' ',n.sub(' ',r.sub(' ',rn.sub(' ',input))))
Run Code Online (Sandbox Code Playgroud)

PS感谢您的好评.' '.join(input.split())似乎是胜利者,因为与使用预编译r'\s+'正则表达式的搜索替换相比,它在我的情况下实际运行速度快了两倍.

Ric*_*dle 12

内置string.split()方法将在空白运行时拆分,因此您可以使用它,然后使用空格连接结果列表,如下所示:

' '.join(my_string.split())
Run Code Online (Sandbox Code Playgroud)

这是一个完整的测试脚本:

TEST = """This
is        a test\twith a
  mix of\ttabs,     newlines and repeating
whitespace"""

print ' '.join(TEST.split())
# Prints:
# This is a test with a mix of tabs, newlines and repeating whitespace
Run Code Online (Sandbox Code Playgroud)