I have the following problem:
given a dictionary where the keys are strings which I will find in another string, and the values are the strings that I want to replace the keys with: for example
replace_dict = {"p": "r"}
str = "p"
str = replace(str, replace_dict)
print(str) # Should output r.
now I have the following code:
pattern = re.compile("|".join(sorted(rep.keys(), key=len, reverse=True)))
ret_string = pattern.sub(lambda m: rep[re.escape(m.group(0))], ret_string)
Now this code does the job, however it has one bug: it replaces substrings for example:
replace_dict = {"p": p1}
str = "p=>p1"
str = replace(str, replace_dict)
print(str) # outputs "p1=>p11", but the output should be p1=>p1
now... I'm trying to figure out how I can tackle this problem without making my regex too complicated.
Any suggestions?
Thanks