Search code examples
pythonregexpython-re

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,'

In the above string, need to add hyphen b/w two words, eg: Device-Name, Device-Family, Device-Type, IP-Address, Serial-No., Current-SMU, Upgrade- Failure-Reason

If I replace with space other places is also replaced with hyphen

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

'\S\s\S' --> is finding the single space b/w 2 words, but not sure how to replace with hyphen without missing any characters

So, please help me to give with regex solution.

Note: there is multiple space available between Device Name & Device Family & Device Type etc.


Solution

  • Use \w to find a character. Then make sure this character is not included in the match by using a positive lookbehind assertion (?<=...) and a lookahead assertion (?=...). If you want to learn more about those assertions then read the documentation of re.

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

    You'll get

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