An re.sub
call always performs an evaluation of the first argument as a regular expression, even if no regular expression features
were used. This has a significant performance cost and therefore should be used with care.
When re.sub
is used, the first argument should be a real regular expression. If it’s not the case, str.replace
does
exactly the same thing as re.sub
without the performance drawback of the regex.
This rule raises an issue for each re.sub
used with a simple string as first argument which doesn’t contains special regex character
or pattern.
Noncompliant code example
init = "Bob is a Bird... Bob is a Plane... Bob is Superman!"
changed = re.sub(r"Bob is", "It's", init) # Noncompliant
changed = re.sub(r"\.\.\.", ";", changed) # Noncompliant
Compliant solution
init = "Bob is a Bird... Bob is a Plane... Bob is Superman!"
changed = init.replace("Bob is", "It's")
changed = changed.replace("...", ";")
Or, with a regex:
init = "Bob is a Bird... Bob is a Plane... Bob is Superman!"
changed = re.sub(r"\w*\sis", "It's", init)
changed = re.sub(r"\.{3}", ";", changed)