ThaoD5
ThaoD5

Reputation: 183

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.

Upvotes: 3

Views: 5283

Answers (4)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210852

If you are looking for one of the fastest ways to do it use intersections of sets:

mySet  = set(['right', 'left', 'front', 'back'])
message = 'right up down left'

if len(mySet & set(message.split())) > 1:
    print('YES')

Upvotes: 2

pp_
pp_

Reputation: 3489

any(x in message for x in myArray)

Evaluates to True if at least one string in myArray is found in message.

sum(x in message for x in myArray) == 1

Evaluates to True if exactly one string in myArray is found in message.

Upvotes: 2

Tomalak
Tomalak

Reputation: 338228

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

Now check the len() of matches.

Upvotes: 3

Bhargav Rao
Bhargav Rao

Reputation: 52081

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

Upvotes: 3

Related Questions