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

Ete*_*ity 154 python string list

我试图避免使用如此多的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"
Run Code Online (Sandbox Code Playgroud)

我希望它是:

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

任何帮助,将不胜感激.

iCo*_*dez 302

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

if link.lower().startswith(("js", "catalog", "script", "katalog")):
Run Code Online (Sandbox Code Playgroud)

来自文档:

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

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

以下是演示:

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

  • 如果它不支持这个,你可以用'any`和genexp来做. (2认同)

小智 19

您也可以使用any(),map()如下所示:

if any(map(l.startswith, x)):
    pass # Do something
Run Code Online (Sandbox Code Playgroud)

或者,使用列表理解:

if any([l.startswith(s) for s in x])
    pass # Do something
Run Code Online (Sandbox Code Playgroud)

  • 不要将列表理解与任何一个一起使用。使用发电机。 (4认同)