0

Can replacement text in re.sub retrieve values from a dictionary?

In the same spirit as another SO's post, with the code

coord_re = re.sub(r"(\d), (\d)", r"\1,\2", coords)

I want to use backreferences in a replacement string as well, except that I want to use string that was referred as \1,\2 as a key to obtain value from some dictionary

For example, I want something similar to this:

d = {...somedict}
coord_re = re.sub(r"(\d), (\d)", d[value of \1]+','+d[value of \2], coords)
chanp
  • 675
  • 7
  • 16

1 Answers1

1

You can use lambda or functions in re.sub:

import re

d = {
    '1': 'a',
    '2': 'b'
}

print( re.sub('(\d), (\d)', lambda g: d[g.group(1)] + ', ' + d[g.group(2)], '1, 2') )

Prints:

a, b

From the documentation:

re.sub(pattern, repl, string, count=0, flags=0)

If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example:

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91