Tre*_*ner 10 python regex whitespace split
我需要在保持空白的同时将字符串拆分为字边界(空白)上的数组.
例如:
'this is a\nsentence'
Run Code Online (Sandbox Code Playgroud)
会成为
['this', ' ', 'is', ' ', 'a' '\n', 'sentence']
Run Code Online (Sandbox Code Playgroud)
我知道str.partition和re.split,但他们都不是我想要的,也没有re.partition.
我应该如何以合理的效率在Python中的空格上分区字符串?
Nik*_*yar 14
试试这个:
s = "this is a\nsentence"
re.split(r'(\W+)', s) # Notice parentheses and a plus sign.
Run Code Online (Sandbox Code Playgroud)
结果将是:
['this', ' ', 'is', ' ', 'a', '\n', 'sentence']
Run Code Online (Sandbox Code Playgroud)