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

Viewed 81

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
2 Answers

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

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

You can use a regular expression.

old_string = "asiatische-Gerichte----wuerzige-Gerichte----vegetarische-Sommerrolle--------Smokey-Pulled-Pork-Burger----"
new_string = re.sub('-{2,}', '-', old_string).strip('-')
print(new_string)
Related