Gabriel Henrique
Gabriel Henrique

Reputation: 48

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

Upvotes: 0

Views: 53

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520978

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

Upvotes: 1

Related Questions