Re: count string replace occurances

2005-06-13 Thread George Sakkis
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

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: count string replace occurances

2005-06-13 Thread William Park
Xah Lee [EMAIL PROTECTED] wrote:
 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.

-- 
William Park [EMAIL PROTECTED], Toronto, Canada
ThinFlash: Linux thin-client on USB key (flash) drive
   http://home.eol.ca/~parkw/thinflash.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: count string replace occurances

2005-06-12 Thread Jeff Epler
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')



pgpAvDTGPd6LT.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list