count string replace occurances

George Sakkis gsakkis at rutgers.edu
Mon Jun 13 02:05:24 EDT 2005


"Jeff Epler" wrote:

> On Sun, Jun 12, 2005 at 04:55:38PM -0700, Xah Lee wrote:
> > if i have
> > mytext.replace(a,b)
> > how to find out many many occurances has been replaced?
>
> The count isn't returned by the replace method.  You'll have to count
> and then replace.
>
> def count_replace(a, b, c):
>     count = a.count(b)
>     return count, s.replace(b, c)
>
> >>> count_replace("a car and a carriage", "car", "bat")
> (2, 'a bat and a batriage')

I thought naively that scanning a long string twice would be almost
twice as slow compared to when counting was done along with replacing.
Although it can done with a single scan, it is almost 9-10 times
slower, mainly because of the function call overhead; the code is also
longer:

import re

def count_replace_slow(aString, old, new):
    count = [0]
    def counter(match):
        count[0] += 1
        return new
    replaced = re.sub(old,counter,aString)
    return count[0], replaced


A good example of trying to be smart and failing :)

George




More information about the Python-list mailing list