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.
matches = [a for a in myArray if a in myStr]
Now check the len() of matches.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With