Skip to content Skip to sidebar Skip to footer

How To Check If Re.sub() Has Successfully Replaced In Python?

Since re.sub() returns the whole modified/unmodified string, is there any way to check if re.sub() has successfully modified the text, without searching the output of re.sub()?

Solution 1:

You can use re.subn which perform the same operation as sub(), but return a tuple (new_string, number_of_subs_made)

If number of modification is 0 i.e. string is not modified.

>>>re.subn('(xx)+', '', 'abcdab')
('abcdab', 0)
>>>re.subn('(ab)+', '', 'abcdab')
('cd', 2)
>>>

Solution 2:

If you have the following code:

importres1="aaa"
result = re.sub("a", "b", s1)

You can check if the call to sub made subsitutions by comparing the id of result to s1 like so:

id(s1) == id(result)

or, which is the same:

s1 is result

This is because strings in python are immutable, so if any substitutions are made, the result will be a different string than the original (ie: the original string is unchanged). The advantage of using the ids for comparison rather than the contents of the strings is that the comparison is constant time instead of linear.

Post a Comment for "How To Check If Re.sub() Has Successfully Replaced In Python?"