How to perform regular expression replacement in Python using dictionary values ​​where the key is another matched object from the same string

My regex needs to match two words in the sentence, but only the second word needs to be replaced. The first word is actually the key to the dictionary from which the replacement for the second word is extracted. In PERL it will look something like this:

$sentence = "Tom boat is blue";
my %mydict = {}; # some key-pair values for name => color
$sentence =~ s/(\S+) boat is (\w+)/$1 boat is actually $mydict{$1}/;
print $sentence;

      

How can this be done in Python?

+3


source to share


1 answer


Something like that:

>>> sentence = "Tom boat is blue"
>>> mydict = { 'Tom': 'green' }
>>> import re
>>> re.sub("(\S+) boat is (\w+)", lambda m: "{} boat is actually {}".format(m.group(1), mydict[m.group(1)]), sentence)
"Tom boat is actually green"
>>> 

      



although it would look better if the lambda was retrieved for a named function.

+3


source







All Articles