Home > Net >  python: reverse a number in a string using regex
python: reverse a number in a string using regex

Time:03-01

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])

CodePudding user response:

The problem is that your "word" variable is a regex expression that is not evaluated yet. You need to evaluate it on your "s" string first, you can do this with re.search method, like this:

import re
s= 'Mary was born in 3102 in England.'
word = re.search('\d{4}',s).group(0)
s_output = s.replace(word,word[::-1]) #Mary was born in 2013 in Englan

CodePudding user response:

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