I have a dictionary like:
dic = { "xl": "xlarg", "l": "larg",'m':'medium'}
and I'd like to use re.sub or similar methods find any string (including a single letter) which are in dic.keys and replace it with the key's value.
def multiple_replace(dict, text):
# Create a regular expression from the dictionary keys
regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
# For each match, look-up corresponding value in dictionary
return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
it works well for single letters in the string e.g. it changes size m to size medium but also it changes letters in words, e.g changes monday to mediumonday
Thanks
"(%s)(?=\W)"where(?=....)is lookahead and\W(capital W) means not word character.