Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: count and replace pattern in string without regex

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?

like image 328
dimid Avatar asked Oct 30 '25 22:10

dimid


1 Answers

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

like image 187
Padraic Cunningham Avatar answered Nov 02 '25 11:11

Padraic Cunningham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!