str.startswith带有要测试的字符串列表 [英] str.startswith with a list of strings to test for

查看:66
本文介绍了str.startswith带有要测试的字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图避免使用太多的if语句和比较,而只使用一个列表,但不确定如何在str.startswith中使用它:

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"

我希望成为的是:

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

任何帮助将不胜感激.

推荐答案

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

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

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

docs :

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

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

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

下面是一个演示:

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

这篇关于str.startswith带有要测试的字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆