用正则表达式在Python中分割字符串

11 投票
3 回答
6120 浏览
提问于 2025-04-16 17:15

我想把一个字符串按照单词的边界(也就是空格)分割成一个数组,同时保留空格。

举个例子:

'this is  a\nsentence'

会变成

['this', ' ', 'is', '  ', 'a' '\n', 'sentence']

我知道有 str.partitionre.split 这两个方法,但它们都不能完全满足我的需求,而且没有 re.partition 这个方法。

我应该如何在Python中以合理的效率在空格处分割字符串呢?

3 个回答

3

试试这个:

re.split('(\W+)','this is  a\nsentence')
4

在正则表达式中,表示空白字符的符号是 '\s',而不是 '\W'

对比一下:

import re


s = "With a sign # written @ the beginning , that's  a\nsentence,"\
    '\nno more an instruction!,\tyou know ?? "Cases" & and surprises:'\
    "that will 'lways unknown **before**, in 81% of time$"


a = re.split('(\W+)', s)
print a
print len(a)
print

b = re.split('(\s+)', s)
print b
print len(b)

会产生

['With', ' ', 'a', ' ', 'sign', ' # ', 'written', ' @ ', 'the', ' ', 'beginning', ' , ', 'that', "'", 's', '  ', 'a', '\n', 'sentence', ',\n', 'no', ' ', 'more', ' ', 'an', ' ', 'instruction', '!,\t', 'you', ' ', 'know', ' ?? "', 'Cases', '" & ', 'and', ' ', 'surprises', ':', 'that', ' ', 'will', " '", 'lways', ' ', 'unknown', ' **', 'before', '**, ', 'in', ' ', '81', '% ', 'of', ' ', 'time', '$', '']
57

['With', ' ', 'a', ' ', 'sign', ' ', '#', ' ', 'written', ' ', '@', ' ', 'the', ' ', 'beginning', ' ', ',', ' ', "that's", '  ', 'a', '\n', 'sentence,', '\n', 'no', ' ', 'more', ' ', 'an', ' ', 'instruction!,', '\t', 'you', ' ', 'know', ' ', '??', ' ', '"Cases"', ' ', '&', ' ', 'and', ' ', 'surprises:that', ' ', 'will', ' ', "'lways", ' ', 'unknown', ' ', '**before**,', ' ', 'in', ' ', '81%', ' ', 'of', ' ', 'time$']
61
15

试试这个:

s = "this is  a\nsentence"
re.split(r'(\W+)', s) # Notice parentheses and a plus sign.

结果会是:

['this', ' ', 'is', '  ', 'a', '\n', 'sentence']

撰写回答