While replacing a pattern in a string,
I specifically need the integer/long value of matching named group.
Example of case and what I tried:
status = {1:'foo', 23:'bar'}
re.sub(
'<status>(?P<id>\d+)',
status.get(int(r'\g<id>')), # ValueError: invalid literal for int() with base 10: '\\g<id>'
# status.get(int(r'\g<id>'.decode())), # ValueError: invalid literal for int() with base 10: '\\g<id>'
# status.get('%d' % r'\g<id>'), # %d format: a number is required, not str
'Tom ran: from <status>1 to <status>23')
Normal casting works well with raw string int(r'22') but it doesn't work in above?
This should work for you:
re.sub(
'<status>(?P<id>\d+)',
lambda m: status.get(int(m.group('id'))),
'Tom ran: from <status>1 to <status>23')
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. @ http://docs.python.org/library/re.html#re.sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With