Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex alternative for join

Tags:

python

regex

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.

like image 542
Shreedhar Manek Avatar asked Dec 01 '22 00:12

Shreedhar Manek


1 Answers

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'
like image 129
nu11p01n73R Avatar answered Dec 05 '22 12:12

nu11p01n73R