Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string contains more than one element from array in Python

I'm using regular expression in my project, and have an array like this :

myArray = [
    r"right",
    r"left",
    r"front",
    r"back"
]

Now I want to check if the string, for example

message = "right left front back"

has more than one match in this array, my purpose here is to have an if being true only if there is only one word matching one of the array.

I tried a lot of things, like this one

if any(x in str for x in a):

but I never make it work with a limited amount.

like image 536
ThaoD5 Avatar asked Mar 06 '26 11:03

ThaoD5


2 Answers

matches = [a for a in myArray if a in myStr]

Now check the len() of matches.

like image 61
Tomalak Avatar answered Mar 08 '26 02:03

Tomalak


You can use sum here. The trick here is that True is calculated as 1 while finding the sum. Hence you can utilize the in directly.

>>> sum(x in message for x in myArray)
4
>>> sum(x in message for x in myArray) == 1
False

if clause can look like

>>> if(sum(x in message for x in myArray) == 1):
...     print("Only one match")
... else:
...     print("Many matches")
... 
Many matches
like image 33
Bhargav Rao Avatar answered Mar 08 '26 00:03

Bhargav Rao