Suppose I have a string string = 'abcdefghi'
and I want the output as 'a-b-c-d-e-f-g-h-i'
I can easily use '-'.join(string)
and get the required output. But what if I want to do the same using regex? How would I do the same using regex?
I am asking because I'm learning to use regex and would like to know how to think in it.
A solution using look arounds will be
>>> import re
>>> str="abcdefghi"
>>> re.sub(r'(?<=\w)(?=\w)', '-', str)
'a-b-c-d-e-f-g-h-i'
(?<=\w)
asserts that a letter is presceded by the postion
(?=\w)
asserts that a letter is followed by the postion
OR
>>> re.sub(r'(?<=.)(?=.)', '-', str)
'a-b-c-d-e-f-g-h-i'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With