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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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
Trueif string starts with theprefix, otherwise returnFalse.prefixcan 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
>>>
Method 2
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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0