count string replace occurances

Jeff Epler jepler at unpythonic.net
Sun Jun 12 21:40:37 EDT 2005


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')

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20050612/7070b050/attachment.sig>


More information about the Python-list mailing list