python:使用正则表达式反转字符串中的数字

python: reverse a number in a string using regex

我有一个字符串如下,

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

我想将此字符串中的数字反转为“2013”​​,因此输出为,

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

我已经完成了以下操作,但没有得到我想要的结果。

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

你可以在这里使用re.sub回调函数:

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.

问题是您的“word”变量是一个尚未计算的正则表达式。您需要首先在您的“s”字符串上对其进行评估,您可以使用 re.search 方法来执行此操作,如下所示:

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