Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to replace letters/words, but I am facing challenges in one aspect of my code

I will be using lloll as an example word.

Here’s my code:

mapping = {'ll':'o','o':'ll'}
string = 'lloll'
out = ' '.join(mapping.get(s,s) for s in string.split())
print(out)

The output should be ollo, but I get lloll. When I write ll o ll, it works, but I don’t want spaces in between the ll and the o, and I don’t want to do something like mapping = {'lloll':'ollo'}.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Not sure if this accounts for all edge cases (what about overlapping matches?), but my current idea is to re.split the string by the mapping’s keys and then apply the mapping.

import re
mapping = {'ll':'o','o':'ll'}
string = 'lloll'
choices = f'({"|".join(mapping)})'
result = ''.join(mapping.get(s, s) for s in re.split(choices, string))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading