python-3.xpython-re

Replacing part of string with re.sub with number and string


I want to replace part of a string based on re.sub method as below

import re
re.sub("([0-9]_F)$", '[0-9]_DO', 'sdsd3_F')

However I fail to manage the numerical part of match which is also a variable. Basically I want to replace 3_F with 3_DO where the number can be any number.

Could you please help with right approach?


Solution

  • Use backreferences:

    re.sub(r'(\d)_F$', r'\1_DO', data)
    

    Parentheses capture part of the match, which can be referred to in the replacement using \1, \2, etc. \d means a digit.