str.startswith with a list of strings to test for

PythonStringList

Python Problem Overview


I'm trying to avoid using so many if statements and comparisons and simply use a list, but not sure how to use it with str.startswith:

if link.lower().startswith("js/") or link.lower().startswith("catalog/") or link.lower().startswith("script/") or link.lower().startswith("scripts/") or link.lower().startswith("katalog/"):
    # then "do something"

What I would like it to be is:

if link.lower().startswith() in ["js","catalog","script","scripts","katalog"]:
    # then "do something"

Any help would be appreciated.

Python Solutions


Solution 1 - Python

str.startswith allows you to supply a tuple of strings to test for:

if link.lower().startswith(("js", "catalog", "script", "katalog")):

From the docs:

> str.startswith(prefix[, start[, end]]) > > Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for.

Below is a demonstration:

>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>

Solution 2 - Python

You can also use any(), map() like so:

if any(map(l.startswith, x)):
    pass # Do something

Or alternatively, using a generator expression:

if any(l.startswith(s) for s in x)
    pass # Do something

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEternityView Question on Stackoverflow
Solution 1 - Pythonuser2555451View Answer on Stackoverflow
Solution 2 - Pythonuser764357View Answer on Stackoverflow