String replace with return value?
Duncan Booth
duncan.booth at invalid.invalid
Mon Oct 11 06:33:05 EDT 2004
Roose wrote:
> How can I do a "".replace operation which tells me if anything was
> actually replaced?
>
> Right now I am doing something like:
>
> if searchTerm in text:
> text = text.replace( searchTerm, 'other' )
Try:
newtext = oldtext.replace(searchTerm, 'other')
if newtext is oldtext:
print "nothing changed"
else:
print "modified text"
You can almost certainly get away with using 'is' here since if replace
doesn't replace anything it simply returns the original string (this is an
implementation detail though, I don't know that there is a cast iron
guarantee that a future implementation won't copy the string if it hasn't
changed, although it would be pretty perverse if it did.)
More information about the Python-list
mailing list