-3

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?

1 Answer 1

-1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. But it is not F with DO
> Basically I want to replace 3_D with 3_DO where the number can be any number.
Actually it was a typo. I have corrected my original post
Ok, adjusted my answer for the same.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.