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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20461847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:30:51  来源:igfitidea点击:

str.startswith with a list of strings to test for

pythonstringlist

提问by Eternity

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 语句和比较,而只是使用一个列表,但不确定如何使用它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.

任何帮助,将不胜感激。

采纳答案by Eternity

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

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

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

From the docs:

文档

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

Return Trueif string starts with the prefix, otherwise return False. prefixcan also be a tuple of prefixes to look for.

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

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

Below is a demonstration:

下面是一个演示:

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

回答by Eternity

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

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

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