What is the non-regex equivalent of subn? I would like to replace a pattern in a string and count how many times was the pattern replaced.
I ended up with:
def replacen(pat, repl, txt):
txt2 = txt.replace(pat, repl)
if (len(pat) != len(repl)):
return (txt2, (len(txt) - len(txt2)) / (len(pat) - len(repl)))
else:
return (txt2, txt.count(pat))
Is there a more elegant solution?
Your own code can simply return txt2 and the count of the pattern:
def replacen(pat, repl, txt):
txt2 = txt.replace(pat, repl)
return txt2, txt.count(pat)
If nothing gets replaced then it is because you found no matching substring so count will return 0 if you replaced 5 substring/pats then txt.count(pat) is going to give you 5
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