如何从空格中删除 in Python "-" 并将它们保留在单词之间?

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

我在 Python 中有一个包含不同单词的字符串。字符串在单词和空格之间用“-”连接,如下例所示。

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

我试过用replace和split的方法去掉空格中的“-”。但是,我只能让它全部删除,但我需要单词之间的连字符。

我的预期结果如下所示:

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

使用 re.sub 将连续出现的 2 个或更多破折号替换为 space:

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

您可以使用正则表达式。

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