str.startswith with a list of strings to test for

后端 未结 2 479
盖世英雄少女心
盖世英雄少女心 2020-11-28 19:34

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.         


        
2条回答
  •  庸人自扰
    2020-11-28 20:13

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

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

    From the docs:

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

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

    Below is a demonstration:

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

提交回复
热议问题