debrises
debrises

Reputation: 105

How to delete a space before and after symbol using regex

As an example, I have a string containing complex numbers with different formatting. I want to delete redundant spaces around "+" but save the spaces between the numbers, so I can convert it then into a list.

I've tried this without any expectations and it doesn't work.

data_str = "15+i10 15+ i10 15 +i10 15 + i10"
data_str = re.sub("\+(?= )", "", data_str)

Desired result is "15+i10 15+i10 15+i10 15+i10"

Thanks for help.

Upvotes: 0

Views: 61

Answers (1)

Nick
Nick

Reputation: 147166

You can just replace any number of spaces around the symbol with nothing i.e.

data_str = "15+i10 15+ i10 15 +i10 15 + i10"
data_str = re.sub("\s*\+\s*", "+", data_str)

Upvotes: 1

Related Questions