如何按 spaces 拆分字符串,但如果它被 python 中的其他 spaces 包围,则保留 space
How to split a string by spaces but keeping the space if it is surrounded by other spaces in python
我试图得到这个结果:
input: "this is a example"
output: ["this", "is", "a", " ", "example"]
但是使用 .split(" ")
我得到这个:
output: ["this", "is", "a", "", "", "example"]
使用 re.findall
我们可以尝试交替匹配单词或 space 两边被 space:
包围的词
inp = "this is a example"
parts = re.findall(r'\w+|(?<=[ ])\s+(?=[ ])', inp)
print(parts) # ['this', 'is', 'a', ' ', 'example']
我试图得到这个结果:
input: "this is a example"
output: ["this", "is", "a", " ", "example"]
但是使用 .split(" ")
我得到这个:
output: ["this", "is", "a", "", "", "example"]
使用 re.findall
我们可以尝试交替匹配单词或 space 两边被 space:
inp = "this is a example"
parts = re.findall(r'\w+|(?<=[ ])\s+(?=[ ])', inp)
print(parts) # ['this', 'is', 'a', ' ', 'example']