Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

regex - Passing a function to re.sub in Python

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

prints:

one testing two three

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...