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()
?
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.
sub() function belongs to the Regular Expressions ( re ) module in Python. It returns a string where all matching occurrences of the specified pattern are replaced by the replace string.
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)
>>>
If you have the following code:
import re
s1 = "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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With