By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,235 Members | 1,057 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,235 IT Pros & Developers. It's quick & easy.

count string replace occurances

P: n/a
if i have
mytext.replace(a,b)
how to find out many many occurances has been replaced?

Xah
xa*@xahlee.org
http://xahlee.org/

Jul 19 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
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')
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.6 (GNU/Linux)

iD8DBQFCrOQSJd01MZaTXX0RAm27AJ47sF1yYVKYIboeSsIcAV QZuhaGPgCfRqRH
mdJtjbwypq/h7XcmVpZOfhs=
=9m3p
-----END PGP SIGNATURE-----

Jul 19 '05 #2

P: n/a
"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

Jul 19 '05 #3

P: n/a
Xah Lee <xa*@xahlee.org> 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 <op**********@yahoo.ca>, Toronto, Canada
ThinFlash: Linux thin-client on USB key (flash) drive
http://home.eol.ca/~parkw/thinflash.html
Jul 19 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.