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
CodePudding user response:
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
CodePudding user response:
This works for me:
def replace_numbers(s, replacements):
# sort replacements by key
# keys are descending
# so '33' gets replaced before '3'
sorted_replacements = sorted(replacements.items(), key=lambda x: x[0], reverse=True)
# iterate over the sorted replacements
for key, value in sorted_replacements:
# replace the key with the value
s = s.replace(str(key), value)
return s
replacements = {
1:"a",
12:"b",
3:"c",
44:"dc",
33:"dd",
31: "ddf"
}
test_str = "def12a 1fc 3 33 feg31"
print(replace_numbers(test_str, replacements))
Output:
defba afc c dd fegddf