String replace with return value?
Fredrik Lundh
fredrik at pythonware.com
Mon Oct 11 06:44:32 EDT 2004
Duncan Booth 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
depends on how you define "if anything was actually replaced", of course:
>>> mytext = "hello"
>>> mytext is mytext.replace("l", "l")
False
>>> mytext == mytext.replace("l", "l")
True
>>> mytext is mytext.replace("x", "x")
True
>>> mytext == mytext.replace("x", "x")
True
</F>
More information about the Python-list
mailing list