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:

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

Leave a Reply