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

python: reverse a number in a string using regex

I have a string as follows,

s= 'Mary was born in 3102 in England.'

I would like to reverse the number in this string to ‘2013’ so the output would be,

s_output = 'Mary was born in 2013 in England.'

I have done the following but do not get the result I am looking for.

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

import re
word = r'\d{4}'
s_output = s.replace(word,word[::-1])

>Solution :

You may use re.sub here with a callback function:

s = 'Mary was born in 3102 in England.'
output = re.sub(r'\d+', lambda m: m.group()[::-1], s)
print(output)  # Mary was born in 2013 in England.
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