Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading