Skip to content
Advertisement

How can I remove in Python “-” from spaces and keep them between words?

I have a string with different words in Python. The string is connected with a “-” between the words and the spaces, as shown in the example below.

asiatische-Gerichte----wuerzige-Gerichte----vegetarische-Sommerrolle--------Smokey-Pulled-Pork-Burger----

I tried using the replace and split method to remove the “-” in the spaces. However, I can only get it to remove them all, but I need the hyphens between the words.

My expected result is shown below:

asiatische-Gerichte wuerzige-Gerichte vegetarische-Sommerrolle Smokey-Pulled-Pork-Burger

Advertisement

Answer

Use re.sub to replace all occurrences of 2 or more dashes in a row with a space:

s = re.sub(r'-{2,}', ' ', s)
Advertisement