String replace with return value?

Gerhard Haering gh at ghaering.de
Mon Oct 11 06:22:42 EDT 2004


On Mon, Oct 11, 2004 at 09:47:48AM +0000, Roose wrote:
> How can I do a "".replace operation which tells me if anything was 
> actually replaced?

You could compare the strings from before and after the replacement.

> Right now I am doing something like:
>
> if searchTerm in text:
>      text = text.replace( searchTerm, 'other' )
>
> But to me this seems inefficient since the 'in' operation will search 
> through the whole string, and then the 'replace' will as well.

Yep. Why not just omit the check and just do the replacement?

> The strings are quite large, they're whole web pages.  Thanks for
> any help.

Then I'd suggest to eventually switch to an existing templating
solution for HTML.

My guess is, however, that you're relatively new to Python. And in
this case, reinventing the wheel a few times is a good way to learn
the language and the libraries. We all did that ;-)

For your particular question, you can also use the re module to
perform string substitutions. And then, there's re.subn or the subn
method of regular expression objects, which will return both the
modified string and the number of substitutions.

Here's a short example for the subn method:

#############################################
import re
import time

modifiedRe = re.compile(r"\$modifieddate")

text = "this webpage was last modified on $modifieddate"

print text
text, replacements = modifiedRe.subn(time.asctime(), text)
print text
print replacements, "replacements made"
#############################################

HTH,

-- Gerhard



More information about the Python-list mailing list