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

How to replace specific part of a substring (numbers) with dictionary values in python?

I have a dictionary:

{1:"a"
 12:"b"
 3:"c"
 44:"dc"
 33:"dd"
 31: "ddf"}

String:

def12a 1fc 3 33 feg31

Output should replace these substrings from the dictionary:

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

defba afc c fefddf

I have tried few things using regex. I am able to replace, when the values are a separate word. But I am not able to do it when it is a substring.

What I tried:
d-> dictionary
s-> string

''.join(d[ch] if ch in d else ch for ch in s)

Thank you for the help

>Solution :

You can use re.sub and after finding num use dict for replacing.

import re
dct = {1:"a", 12:"b", 3:"c", 44:"dc", 33:"dd", 31: "ddf"}
st = 'def12a 1fc 3 33 feg31'
res = re.sub(r'(\d+)', lambda x: dct[int(x.group())], st)
print(res)

defba afc c dd fegddf
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