str.startswith带有要测试的字符串列表

问题:str.startswith带有要测试的字符串列表

我试图避免使用那么多的if语句和比较,而只使用一个列表,但不确定如何将其用于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"

我希望它是:

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

任何帮助,将不胜感激。

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.


回答 0

str.startswith 允许您提供一个字符串元组来测试:

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

文档

str.startswith(prefix[, start[, end]])

返回True如果字符串开始用prefix,否则返回Falseprefix也可以是要查找的前缀的元组。

下面是一个演示:

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

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
>>>

回答 1

你也可以使用any()map()就像这样:

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

或者,使用生成器表达式

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

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