Benny
Benny

Reputation: 649

How to do regex 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 a sentence, but only the second word needs to be replaced. The first word is actually a key to a dictionary where the substitute for the second word is fetched. In PERL it would look something like:

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

How can this be done in python?

Upvotes: 3

Views: 2442

Answers (1)

Duncan
Duncan

Reputation: 95652

Something like this:

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

though it would look better with the lambda extracted to a named function.

Upvotes: 3

Related Questions