count string replace occurances

J

Jeff Epler

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)
(2, 'a bat and a batriage')


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.6 (GNU/Linux)

iD8DBQFCrOQSJd01MZaTXX0RAm27AJ47sF1yYVKYIboeSsIcAVQZuhaGPgCfRqRH
mdJtjbwypq/h7XcmVpZOfhs=
=9m3p
-----END PGP SIGNATURE-----
 
G

George Sakkis

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
 
W

William Park

Xah Lee said:
if i have
mytext.replace(a,b)
how to find out many many occurances has been replaced?

If 'a' and 'b' are different length,
- Count the string length, before and after. The difference should
be multiple of difference between length of 'a' and 'b'.

If they are same length,
- Split 'mytext', and count items.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top