Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find exact match in list of strings

very new to this so bear with me please...

I got a predefined list of words

checklist = ['A','FOO']

and a words list from line.split() that looks something like this

words = ['fAr', 'near', 'A']

I need the exact match of checklist in words, so I only find 'A':

if checklist[0] in words:

That didn't work, so I tried some suggestions I found here:

if re.search(r'\b'checklist[0]'\b', line): 

To no avail, cause I apparently can't look for list objects like that... Any help on this?

like image 947
origamisven Avatar asked Nov 11 '15 05:11

origamisven


People also ask

How do you match a string to a list in Python?

Python Find String in List using count() We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1.

How do I check if a string matches in Python?

Python strings equality can be checked using == operator or __eq__() function. Python strings are case sensitive, so these equality check methods are also case sensitive.

How do you use exact match in JavaScript?

We can match an exact string with JavaScript by using the JavaScript string's match method with a regex pattern that has the delimiters for the start and end of the string with the exact word in between those.

How do I find a match in Python?

match() function of re in Python will search the regular expression pattern and return the first occurrence. The Python RegEx Match method checks for a match only at the beginning of the string. So, if a match is found in the first line, it returns the match object.


1 Answers

Using a set would be much faster than iterating through the lists.

checklist = ['A', 'FOO']
words = ['fAr', 'near', 'A']
matches = set(checklist).intersection(set(words))
print(matches)  # {'A'}
like image 132
binarysubstrate Avatar answered Sep 28 '22 02:09

binarysubstrate