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

4 投票
3 回答
4361 浏览
提问于 2025-04-15 13:28

有没有一种跨平台的库函数,可以把多行字符串压缩成一行字符串,并且去掉重复的空格呢?

我写了一些代码,但我在想是否有一个标准的函数可以直接导入,可能还用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))))

顺便说一下,感谢大家的好建议。' '.join(input.split()) 似乎是最好的选择,因为在我的情况下,它的运行速度比用预编译的 r'\s+' 正则表达式进行查找替换快了大约两倍。

3 个回答

0
multi_line.replace('\n', '')

这样就可以了。'\n' 是 Python 中一个通用的换行符。

4

你想法是对的,只是需要更仔细地看看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'
12

内置的 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

撰写回答