"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Efficiently Check for String Extensions Within a String?

How to Efficiently Check for String Extensions Within a String?

Published on 2024-11-08
Browse:126

How to Efficiently Check for String Extensions Within a String?

Finding Strings within a String

Given a string url_string and a list of extensions extensionsToCheck, determine if any of the extensions appear in the string. A straightforward approach would be to iterate through the list and check for each extension:

for extension in extensionsToCheck:
    if extension in url_string:
        print(url_string)

Alternatively, you can employ a more concise method using a generator and the any function, which evaluates if any of the conditions in the generator are true:

if any(ext in url_string for ext in extensionsToCheck):
    print(url_string)

In this solution, a generator creates a sequence by iterating through extensionsToCheck, checking for each element if it exists within url_string. If any of these checks return true, the any function evaluates to true, and the url_string is printed.

It's important to note that this method checks for the presence of the extensions within url_string regardless of their position. If it's crucial to check for the extension's position, consider using suffixes as described in the answer provided by @Wladimir Palant.

Latest tutorial More>

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