Checking List Element Presence in a String in Python
One common task in Python programming is verifying whether a string includes an element from a given list. A traditional approach employs a for loop, as exemplified in the code below:
extensionsToCheck = ['.pdf', '.doc', '.xls']
for extension in extensionsToCheck:
if extension in url_string:
print(url_string)
While functional, this method may seem cumbersome. A more succinct approach involves utilizing a generator coupled with the any() function, which evaluates its arguments until encountering the first True:
if any(ext in url_string for ext in extensionsToCheck):
print(url_string)
Using String Formatting
Alternatively, if the order of the elements in the list matters, string formatting can be employed. For instance:
url_string = 'sample.doc'
extensionsToCheck = ['.pdf', '.doc', '.xls']
if f'.{url_string.split(".")[-1]}' in extensionsToCheck:
print(url_string)
Here, the .split() method separates the URL string based on the period, and the [-1] index selects the last element, representing the file extension. The f-string then formats the extension into the correct form for comparison.
Note: Using any() in this context only checks if any element from the list is present in the string, regardless of its position. If the specific location of the element matters, more precise methods, such as regex or string manipulation functions, should be considered.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3