Case insensitive list remove call


10th of April 2006

Often when working with lists of strings in python you might want to deal with the strings in a case insensitive manner. Today I had to fix an issue where I couldn't use somelist.remove(somestring) because the somestring variable might be in there but of a different (case)spelling.

Here was the original code:: def ss(s): return s.lower().strip() if ss(name) in names: foo(name + " was already in 'names'") names.remove(name)

The problem there is that you get an ValueError if the name variable is "peter" and the names variable is ["Peter"]. Here is my solution. Let me know what you think:

 def ss(s):
    return s.lower().strip()

 def ss_remove(list_, element):
    correct_element = None
    element = ss(element)
    for item in list_:
        if ss(item) == element:
            list_.remove(item)
            break

 L = list('ABC')
 L.remove('B')
 #L.remove('c') # will fail
 ss_remove(L, 'c') # will work
 print L # prints ['A']

Might there be a better way?

UPDATE Check out Case insensitive list remove call (part II)



Comment

Show all 13 comments
 
Name:
Email:
hide my email address.

Your email address will be encoded to prevent email-extraction spiders from reading it so you won't get spammed if you decide to show your email address.