Try this comprehension:
>>> x = "Romeo and Juliet"
>>> y = [word for word in x.split() if word.lower() != "and"]
>>> y
['Romeo', 'Juliet']
>>> x = "Romeo aND Juliet"
>>> y = [word for word in x.split() if word.lower() != "and"]
>>> y
['Romeo', 'Juliet']
The key is applying lower()
when you compare your word to the key. This normalizes what you might find into a form you'd can expect. So even if key = "aND"
or key = "AnD"
, key.lower() = "and"
regardless.
Just for completeness, you could do this with functions other than lower()
and end up with an equivalent solution so long as your key matches. Some examples:
Some notes:
As Sunny Nada pointed out, this approach gives less than ideal results if the names ahve spaces (x = "Joe Smith and Tom" >>> ["Joe", "Smith", "Tom"]
). If this is not what you want, you'll need a more robust method (like re
)
To make your approach work you could change if x[i:i+3] == 'and' or x[i:i+3] == 'aNd':
to if x[i:i+3] in ["and", "AND", "aNd", ...etc]:
. This approach is typically considered better form for testing multiple values (or
conditions). Alternatively, you could use the if
statement that I use in my comprehension and get similar results (if x[i:i+3].lower() == "and":
)
One final suggestion (mostly for fun) which will work with multi-word names and avoids re
>>> y = map(lambda s: s.strip(), map(lambda s: s.title(), x.lower().split('and')))
>>> y
['Romeo', 'Juliet']
Note that this is probably an abuse of map()
and lambda
functions