views:

9470

answers:

9

What's the best way to do case insensitive string comparison in Python?

I would like to encapsulate comparison of a regular strings to a repository string using in a very simple and pythonic way. I also would like to have ability to look up values in a dict hashed by strings using regular python strings. Much obliged for advice.

+15  A: 
string1 = 'Hello'
string2 = 'hello'

if string1.lower() == string2.lower():
    print "The strings are the same (case insensitive)"
else:
    print "The strings are not the same (case insensitive)"
Harley
I believe you have a typo: should be string1.lower()
Soldarnal
A: 

The usual approach is to uppercase the strings or lower case them for the lookups and comparisons. For example:

>>> "hello".upper() == "HELLO".upper()
True
>>>
Glomek
+2  A: 

How about converting to lowercase first? you can use string.lower().

Camilo Díaz
A: 
lower(string1) == lower(string2)
lower(string1) <  lower(string2)
lower(string1) >  lower(string2)
Sparr
You might want to mention that you need to import lower() from string for this to work. Also note that lower() is no longer available in Python 3.
Matthew Trevor
A: 

You could subclass the builtin "str" if you need to compare a lot and dont want to clutter your code all over with .lower()

class ci_str(str):
    def __eq__(self, other):
        return self.lower() == other.lower()

a = ci_str("Hello World")
b = ci_str("hello world")
c = ci_str("foo bar")
print a == b
print b == c

>>> 
True
False
truppo
complex solution to a simple problem
orip
+4  A: 

Please see Ignore case in Python strings

ΤΖΩΤΖΙΟΥ
A: 
def insenStringCompare(s1, s2):
    """ Method that takes two strings and returns True or False, based
        on if they are equal, regardless of case."""
    try:
        return s1.lower() == s2.lower()
    except AttributeError:
        print "Please only pass strings into this method."
        print "You passed a %s and %s" % (s1.__class__, s2.__class__)
Patrick Harrington
A: 

What about the performance of the str.lower method? I am running a batch process against a small database (500 MB of text) and using this method for case-insensitive comparison is taking about 3 times as along as the case-sensitive comparison did.

In C there are functions for doing case-insensitive comparison which do not need to alter the strings, such as stricmp. Is there no equivalent for Python?

Kurt
if you have a question, ask question. this is not a forum, please, delete this non-answer.
SilentGhost
A: 
import re
re.match('what to find', 'text to search through', re.IGNORECASE) is None
Mr Temp