Python,如何在给定字符串中添加连字符b/w两个单词

Ptyhon, how to add a hyphen b/w two words in a given string

test_str = 'S.No   Device Name        Device Family       Device Type           Device Role   IP Address   Location                 Serial No.     Current    Current SMU    Upgrade Failure Reason,'

在上面的字符串中,需要加上连字符b/w两个字, 例如:设备名称、设备系列、设备类型、IP 地址、序列号、当前 SMU、升级失败原因

如果我替换成space其他地方也替换成连字符

replacedText = re.sub(r'\S\s\S' , r'', test_str)

'\S\s\S' --> 正在查找单个 space b/w 2 个单词,但不确定如何在不丢失任何字符的情况下用连字符替换

所以,请帮我给出正则表达式解决方案。

注意:设备名称&设备系列&设备类型等之间有多个space可用

使用\w找一个角色。然后通过使用 正后向断言 (?<=...) 前向断言 [=13= 确保该字符不包含在匹配中].如果您想了解有关这些断言的更多信息,请阅读 documentation of re.

replaced_text = re.sub(r'(?<=\w) (?=\w)', r'-', test_str)

你会得到

S.No Device-Name Device-Family Device-Type Device-Role IP-Address Location Serial-No. Current Current-SMU Upgrade-Failure-Reason,