40

我有一个字符串:

myStr = "Chicago Blackhawks vs. New York Rangers"

我还有一个清单:

myList = ["Toronto Maple Leafs", "New York Rangers"]

使用 endswith() 方法,我想编写一个 if 语句来检查 myString 是否以 myList 中的任一字符串结尾。我有基本的 if 语句,但我对应该在括号中放入什么来检查这一点感到困惑。

if myStr.endswith():
    print("Success")
4

3 回答 3

80

endswith()接受一个后缀元组。您可以将列表转换为元组,也可以首先使用元组而不是列表。

In [1]: sample_str = "Chicago Blackhawks vs. New York Rangers"

In [2]: suffixes = ("Toronto Maple Leafs", "New York Rangers")

In [3]: sample_str.endswith(suffixes)
Out[3]: True

来自文档:

str.endswith(suffix[, start[, end]])

如果字符串以指定的后缀结尾,则返回 True,否则返回 False。suffix 也可以是要查找的后缀元组。使用可选开始,从该位置开始测试。使用可选结束,在该位置停止比较。

于 2016-02-19T17:06:31.670 回答
13

您可以使用关键字any

if any(myStr.endswith(s) for s in myList):
    print("Success")
于 2016-02-19T17:07:03.250 回答
0

你可以这样做:)

for i in myList:
    if myStr.endswith(i):
        print(myStr + " Ends with : " + i)
于 2016-02-19T18:29:06.370 回答