Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find what matched in any() with Python?

Tags:

python

any

I'm working in Python, using any() like so to look for a match between a String[] array and a comment pulled from Reddit's API.

Currently, I'm doing it like this:

isMatch = any(string in comment.body for string in myStringArray)  

But it would also be useful to not just know if isMatch is true, but which element of myStringArray it was that had a match. Is there a way to do this with my current approach, or do I have to find a different way to search for a match?

like image 984
Danny B Avatar asked Jan 18 '17 19:01

Danny B


People also ask

What does match () do in Python?

match() both are functions of re module in python. These functions are very efficient and fast for searching in strings. The function searches for some substring in a string and returns a match object if found, else it returns none.

How do I find the matching pattern in Python?

Use re. match() to check if a string matches a pattern A pattern specifies a sequence of characters that can be matched to a string and follows the regular expression syntax in Python. re. match(pattern, string) tests if the regex pattern matches string .

How do you check if a string is matched?

If you need to know if a string matches a regular expression RegExp , use RegExp. prototype. test() . If you only want the first match found, you might want to use RegExp.

What is the regular expression function to match all occurrences of a string in Python?

findall. findall() is probably the single most powerful function in the re module. Above we used re.search() to find the first match for a pattern. findall() finds *all* the matches and returns them as a list of strings, with each string representing one match.


2 Answers

For python 3.8 or newer use Assignment Expressions

if any((match := string) in comment.body for string in myStringArray):
    print(match)
like image 113
airborne Avatar answered Oct 22 '22 16:10

airborne


You could use next with default=False on a conditional generator expression:

next((string for string in myStringArray if string in comment.body), default=False)

The default is returned when there is no item that matched (so it's like any returning False), otherwise the first matching item is returned.

This is roughly equivalent to:

isMatch = False  # variable to store the result
for string in myStringArray:
    if string in comment.body:
        isMatch = string
        break  # after the first occurrence stop the for-loop.

or if you want to have isMatch and whatMatched in different variables:

isMatch = False  # variable to store the any result
whatMatched = '' # variable to store the first match
for string in myStringArray:
    if string in comment.body:
        isMatch = True
        whatMatched = string
        break  # after the first occurrence stop the for-loop.
like image 13
MSeifert Avatar answered Oct 22 '22 17:10

MSeifert