algorithm does python use to compare two strings

Robert Kern robert.kern at gmail.com
Sun Apr 29 13:26:41 EDT 2012


On 4/29/12 5:34 PM, Terry Reedy wrote:
> On 4/29/2012 6:05 AM, Terry Reedy wrote:
>> On 4/29/2012 3:59 AM, J. Mwebaze wrote:
>>> I am just wondering which specific algorithm does python use to compare
>>> two strings.
>>
>> 'Python' does not use algorithms, implementations do. CPython may check
>> id and or hash before doing a character-by-char comparison (or perhaps
>> multiple chars at a time).

Identity is checked first, but hashes aren't.

> I think all the sequence comparisons check for equality of len() before doing
> item by item comparison.

== does, but != and the ordering comparisons don't, at least in the 2.x str 
implementation. unicode objects don't compare lengths first because the rich 
comparison function really just defers to an old-style -1,0,+1 compare function. 
In Python 3.x, bytes objects behave the same, but str objects *do* the length 
comparison for both == and != (but not the others, naturally). <phew>

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list