Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a function to re.sub in Python

Tags:

python

regex

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?

like image 448
VPeric Avatar asked Sep 11 '13 09:09

VPeric


People also ask

How do you use the RE sub function in Python?

re. sub() function is used to replace occurrences of a particular sub-string with another sub-string. This function takes as input the following: The sub-string to replace. The sub-string to replace with.

Which of following is correct syntax for re sub () in Python?

The syntax for re. sub() is re. sub(pattern,repl,string). That will replace the matches in string with repl.

Does re sub replace all occurrences?

By default, the count is set to zero, which means the re. sub() method will replace all pattern occurrences in the target string.


1 Answers

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 
like image 187
alecxe Avatar answered Sep 19 '22 10:09

alecxe