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)
小智 19
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)
| 归档时间: |
|
| 查看次数: |
105354 次 |
| 最近记录: |