Home >Backend Development >Python Tutorial >How to Efficiently Check if a String Contains an Element from a List in Python?
Checking String Element Existence in a List in Python
This question seeks an elegant method to determine if a string contains an element from a specified list without employing a for loop. The following code exemplifies the issue:
The user's attempt to use a logical OR operator, as in C/C , failed to provide the desired result.
Elegant Solution Using Generators and Any
A more sophisticated solution leverages a generator and the any function, which evaluates to True as soon as any element in the list is found within the string:
In this code, a generator expression produces a series of boolean values indicating whether each element in extensionsToCheck exists in url_string. The any function then returns True if any of these boolean values is True.
Caution When Checking End Position
It's important to note that this solution does not account for the position of the matching string within url_string. For instance, if the list contained .com and the string under examination was example.company.com, the solution would return True even though .com appears in the middle of the string.
If the precise location of the matching string is a concern, as it often is with URLs, consider utilizing the solution provided by @Wladimir Palant, which involves examining file extensions in the context of URLs.
The above is the detailed content of How to Efficiently Check if a String Contains an Element from a List in Python?. For more information, please follow other related articles on the PHP Chinese website!