代码之家  ›  专栏  ›  技术社区  ›  Evgeny

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

  •  4
  • Evgeny  · 技术社区  · 16 年前

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

    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))))
    

    另外,谢谢你的观察。 ' '.join(input.split()) 似乎是赢家,因为在我的例子中,它实际运行速度比使用预编译的搜索替换快了大约两倍 r'\s+' 正则表达式。

    3 回复  |  直到 16 年前
        1
  •  12
  •   RichieHindle    16 年前

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

    ' '.join(my_string.split())
    

    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
    
        2
  •  4
  •   Unknown    16 年前

    您的想法是正确的,您只需要更仔细地阅读python手册:

    import re
    somewhitespace = re.compile(r'\s+')
    TEST = """This
    is        a test\twith a
      mix of\ttabs,     newlines and repeating
    whitespace"""
    
    somewhitespace.sub(' ', TEST)
    
    'This is a test with a mix of tabs, newlines and repeating whitespace'
    
        3
  •  0
  •   SilentGhost    16 年前
    multi_line.replace('\n', '')
    

    我会做好的。 '\n' 是python中的通用行尾字符。