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

Time:06-01

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

CodePudding user response:

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

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

CodePudding user response:

You can use a regular expression.

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