在 Python 中将函数传递给 re.sub [英] Passing a function to re.sub in Python
问题描述
我的字符串中某处包含一个数字,我试图用它们的文字符号(即 3 -> 3)替换这个数字.我有一个功能可以做到这一点.现在的问题是找到字符串中的数字,同时保持字符串的其余部分完好无损.为此,我选择使用 re.sub
函数,它可以接受可调用".但是,传递给它的对象是内部 _sre.SRE_Match
并且我不确定如何处理它.我的函数接受数字或其字符串表示.
I have strings that contain a number somewhere in them and I'm trying to replace this number with their word notation (ie. 3 -> three). I have a function that does this. The problem now is finding the number inside the string, while keeping the rest of the string intact. For this, I opted to use the re.sub
function, which can accept a "callable". However, the object passed to it is the internal _sre.SRE_Match
and I'm not sure how to handle it. My function accepts a number or its string representation.
我应该如何编写一些辅助函数来桥接 re.sub
调用与我的函数执行所需的处理?或者,有没有更好的方法来做我想做的事?
How should I write some helper function which can be used to bridge the re.sub
call with my function doing the required processing? Alternatively, is there a better way to do what I want?
推荐答案
你应该调用 group()
来获取匹配的字符串:
You should call group()
to get the matching string:
import re
number_mapping = {'1': 'one',
'2': 'two',
'3': 'three'}
s = "1 testing 2 3"
print re.sub(r'\d', lambda x: number_mapping[x.group()], s)
印刷品:
one testing two three
这篇关于在 Python 中将函数传递给 re.sub的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!