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