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
str.startswith with a list of strings to test for
提问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 theprefix, otherwise returnFalse.prefixcan also be a tuple of prefixes to look for.
str.startswith(prefix[, start[, end]])返回
True如果字符串开始用prefix,否则返回False。prefix也可以是要查找的前缀元组。
Below is a demonstration:
下面是一个演示:
>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>

