python:使用正则表达式反转字符串中的数字
我有一个如下字符串,
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])
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])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在此处使用
re.sub
和回调函数:You may use
re.sub
here with a callback function:问题是您的“word”变量是一个尚未评估的正则表达式。您需要首先在“s”字符串上评估它,您可以使用 re.search 方法来执行此操作,如下所示:
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: