How to Efficiently Check for String Extensions Within a String?

Barbara Streisand
Release: 2024-11-05 05:11:02
Original
674 people have browsed it

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:

<code class="python">for extension in extensionsToCheck:
    if extension in url_string:
        print(url_string)</code>
Copy after login

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:

<code class="python">if any(ext in url_string for ext in extensionsToCheck):
    print(url_string)</code>
Copy after login

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.

The above is the detailed content of How to Efficiently Check for String Extensions Within a String?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template