4

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?

1

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

Its very funny rally some times we missed the answers in our life because of those simplicity :-D
right, but I don't want to use count unless I have to (for efficiency considerations)
I doubt you'll get more efficient than count.
count is at least O(n) while checking the lengths is O(1)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.