String replace with return value?

Roose moof at boof.moof
Tue Oct 12 01:26:46 EDT 2004


Gerhard Haering wrote:
> 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?


I thought of that, but don't you see, that's pretty much the same thing. 
  It's a question of doing an 'in' and a replace vs. a compare and a 
replace.  Both in and equality comparison are linear operations, so 
choosing over the other doesn't really matter.  A speedup can still be 
obtained by traversing the string once instead of twice.

Now, the person who suggested using 'is' (which is constant time) was 
onto something, but alas replace doesn't work like that.  As someone 
demonstrated, it returns a new string in any case.


> 
> 
>>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.

That doesn't apply, since I'm not generating web pages.  I'm 
transforming existing ones in a spider kind of program.

> 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.

Thank you, that's just what I was looking for.

Roose



More information about the Python-list mailing list