Jeff Epler said:
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)
(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