String replace with return value?
Duncan Booth
duncan.booth at invalid.invalid
Tue Oct 12 04:39:12 EDT 2004
Roose wrote:
> 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.
No, it only returns a new string if it actually does a replacement.
Frederick Lundh confused the issue by pointing out that a replace can do a
replacement on a string but leave it unchanged. Provided you can guarantee
that the original string and replacement string are different this won't
matter.
To keep Frederick happy, you could change my example to:
if searchTerm == replacement:
newtext = oldtext
else:
newtext = oldtext.replace(searchTerm, replacement)
if newtext is oldtext:
print "nothing changed"
else:
print "modified text"
I will be surprised though if the overhead of comparing strings using '=='
even if they are large web pages if measurable in terms of either server
loading or time to retrieve a page.
More information about the Python-list
mailing list