0

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

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.