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

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"]


Solution 1:[1]

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']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tim Biegeleisen