Home > OS >  How to split a string by spaces but keeping the space if it is surrounded by other spaces in python
How to split a string by spaces but keeping the space if it is surrounded by other spaces in python

Time:05-10

I'm trying to get this result:

input: "this is a   example"
output: ["this", "is", "a", " ", "example"]

But using .split(" ") I am getting this:

output: ["this", "is", "a", "", "", "example"]

CodePudding user response:

Using re.findall we can try alternatively matching words or spaces which are surrounded on both sides by space:

inp = "this is a   example"
parts = re.findall(r'\w |(?<=[ ])\s (?=[ ])', inp)
print(parts)  # ['this', 'is', 'a', ' ', 'example']
  • Related