regex - Case insensitive matching python -


i want match items 1 list in without worrying case sensitivity.

mylist1 = ['fbh_q1ba8', 'fhh_q1ba9', 'fbh_q1ba10','hoot'] mylist2 = ['fbh_q1ba8', 'trick','fbh_q1ba9', 'fbh_q1ba10','maj','joe','civic'] 

i doing before:

for item in mylist2:     if item in mylist1:         print "true"     else:         print "false" 

but fails because not case sensitive.

i aware of re.match("test", "test", re.ignorecase) how can apply example?

normalize case str.lower():

for item in mylist2:     print item.lower() in mylist1 

the in containment operator returns true or false, easiest print that:

>>> mylist1 = ['fbh_q1ba8', 'fhh_q1ba9', 'fbh_q1ba10','hoot'] >>> mylist2 = ['fbh_q1ba8', 'trick','fbh_q1ba9', 'fbh_q1ba10','maj','joe','civic'] >>> item in mylist2: ...     print item.lower() in mylist1 ...  true false false true false false false 

if mylist1 contains mixed case values, you'll need make loop explicit; use generator expression produce lowercased values; testing against ensures many elements lowercased needed find match:

for item in mylist2:     print item.lower() in (element.lower() element in mylist1) 

demo

>>> mylist1 = ['fbh_q1ba8', 'fhh_q1ba9', 'fbh_q1ba10','hoot'] >>> item in mylist2: ...     print item.lower() in (element.lower() element in mylist1) ...  true false false true false false false 

another approach use any():

for item in mylist2:     print any(item.lower() == element.lower() element in mylist1) 

any() short-circuits; true value has been found (a matching element found), generator expression iteration stopped early. have lowercase item each iteration, less efficient.

another demo:

>>> item in mylist2: ...     print any(item.lower() == element.lower() element in mylist1) ...  true false false true false false false 

Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -