Darshan Chaudhary
Darshan Chaudhary

Reputation: 2233

re.sub() error related to MatchObject.group()

I have a very simple job for re.sub(), but am not able to get it to work correctly.

import re
print re.sub(r"\d+", lambda x:x, "1 2 3 4 5")

The matched strings should be printed as-is, so the expected output is:

1 2 3 4 5

The error I am getting is :

Traceback (most recent call last):
  File "_.py", line 2, in <module>
    print re.sub(r"\d+", lambda x:x, "1 2 3 4 5")
  File "/home/radar/anaconda/lib/python2.7/re.py", line 155, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: sequence item 0: expected string, _sre.SRE_Match found

Upvotes: 2

Views: 684

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1122152

The replacement function is passed a match object by re.sub(). You return that match object directly, while you must return a string instead; after all that is what is going to be used to replace (substitute) the original match.

You could return the matched text, via the MatchObject.group() method:

print re.sub(r"\d+", lambda x: x.group(), "1 2 3 4 5")

You have not clearly stated you expected to happen, however; the above will return the original string, as it replaces each digit with itself:

>>> re.sub(r"\d+", lambda x: x.group(), "1 2 3 4 5")
'1 2 3 4 5'

or you could increment the number by one (which requires conversion to an integer, then after manipulation, conversion back to a string):

>>> re.sub(r"\d+", lambda x: str(int(x.group()) + 1), "1 2 3 4 5")
'2 3 4 5 6'

Upvotes: 3

Sakib Ahammed
Sakib Ahammed

Reputation: 2480

re.sub(r"\d+", lambda x: x.group(), "1 2 3 4 5")

Upvotes: 1

Related Questions