Case insensitive list remove call
10 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)