[Tutor] String comparison
alan.gauld@bt.com
alan.gauld@bt.com
Thu, 8 Aug 2002 12:40:59 +0100
> How do I perform a string comparison in Python.
if str1 == str2:...
if str1 < str2:....
etc
Also using cmp()
cmp(str1,str2)
returns -1,0,1 for less than, equal, greater than...
> This is because of the ASCII values of upper case letters
> which is smaller than those of lower case ones. Is there any
> command which will compare irrespective of the cases.
No, but you can convcert case with the upper() and
lower() methods of string objects:
str1 = "Hero"
str2 = "here"
cmp(str1,str2)
str1 will be less that str2 coz of the uppercase H.
Now try
cmp(str1.upper(),str2.upper())
str2 should be lower because it ends in 'e'...
HTH,
Alan G.