[Tutor] String comparison

Don Arnold darnold02@sprynet.com
Thu, 8 Aug 2002 06:02:24 -0500


----- Original Message -----
From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu>
To: "Yigal Duppen" <yduppen@xs4all.nl>
Cc: "Tutor" <tutor@python.org>
Sent: Thursday, August 08, 2002 5:43 AM
Subject: Re: [Tutor] String comparison


>
>
> On Thu, 8 Aug 2002, Yigal Duppen wrote:
>
> > Python has no command for comparing strings irrespective of case; the
> > usual approach is to lowercase (or uppercase) the strings before
> > comparing them:
> >
> > >>> a = "a"
> > >>> b = "B"
> > >>> a < b
> > 0
> > >>> a.lower() < b.lower()
> > 1
> > >>> a.upper() < b.upper()
> > 1
> > >>> a
> > 'a'
> > >>> b
> > 'B'
> >
> > As you can see, both upper and lower return copies; they leave the
> > original strings intact. Strings are immutable objects in Python.
>

<snipped Java stuff>
>
> Sorry, I get sidetracked a lot.  *grin* Back to Python: we can always
> write a function to make things look nicer:
>
> ###
> def cmpIgnoresCase(s1, s2):
>     """Returns a negative value if s1 is smaller than s2, zero if the two
> strings are equal, and a positive value if s1 is greater than s2, case
> insensitively"""
>     return cmp(s1.upper(), s2.upper())
> ###
>

I'm not sure if anyone has mentioned it yet, but to actually have your
sort() method use this comparison function, you'll need to supply it as an
argument to sort():

>>> list1 = ['E','d','C','b','A']
>>> list1.sort(CaseInsensitiveCmp)
>>> print list1
['A', 'b', 'C', 'd', 'E']

Hope that helps,
Don