This question is asking 2 very different things:
- What is the easiest way to compare strings in Python, ignoring case?
- I guess I'm looking for an equivalent to C's stricmp().
Since #1 has been answered very well already (ie: str1.lower() < str2.lower()) I will answer #2.
def strincmp(str1, str2, numchars=None):
result = 0
len1 = len(str1)
len2 = len(str2)
if numchars is not None:
minlen = min(len1,len2,numchars)
else:
minlen = min(len1,len2)
#end if
orda = ord('a')
ordz = ord('z')
i = 0
while i < minlen and 0 == result:
ord1 = ord(str1[i])
ord2 = ord(str2[i])
if ord1 >= orda and ord1 <= ordz:
ord1 = ord1-32
#end if
if ord2 >= orda and ord2 <= ordz:
ord2 = ord2-32
#end if
result = cmp(ord1, ord2)
i += 1
#end while
if 0 == result and minlen != numchars:
if len1 < len2:
result = -1
elif len2 < len1:
result = 1
#end if
#end if
return result
#end def
Only use this function when it makes sense to as in many instances the lowercase technique will be superior.
I only work with ascii strings, I'm not sure how this will behave with unicode.