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

发布于 2025-01-11 00:58:36 字数 311 浏览 0 评论 0原文

我有一个如下字符串,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谁许谁一生繁华 2025-01-18 00:58:37

您可以在此处使用 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.

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.
独自←快乐 2025-01-18 00:58:36

问题是您的“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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文