user1899415
user1899415

Reputation: 3125

Python: re module to replace value in dictionary

I started looking at the handy re module available in Python today, and hoping I could get help with re.sub

My file:

avid "Av.Id
fated "fEIt.Id
leaded "lEd.Id
wicked "wIk.Id

I want to sub if match "(v|t|d|k)\.Id" then change to "\.(v|t|d|k)Id" so that output looks like:

avid "A.vId
fated "fEI.tId
leaded "lE.dId
wicked "wI.kId

I could match my string fine with re.search however I'm stuck at how I can do the actual replacement when the letter is different every time (v, t, d, k, etc). Thanks for any help.

Upvotes: 2

Views: 72

Answers (1)

alecxe
alecxe

Reputation: 473853

Use re.sub() and reference the saved group (v|t|d|k) using \g<1> syntax:

import re

PATTERN = re.compile('(v|t|d|k)\.Id')
with open('input.txt') as f:
    for line in f:
        print PATTERN.sub(".\g<1>Id", line)

It prints:

avid "A.vId
fated "fEI.tId
leaded "lE.dId
wicked "wI.kId

Upvotes: 1

Related Questions