Python的endswith()可以用于多个字符串吗?

55

我有一个字符串:

myStr = "Chicago Blackhawks vs. New York Rangers"

我也有一个列表:

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

使用endswith()方法,我想写一个if语句来检查myString是否以myList中任意一个字符串结尾。我有一个基本的if语句,但我不知道应该在括号里放什么来进行检查。

if myStr.endswith():
    print("Success")
3个回答

102

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。 后缀也可以是要查找的后缀元组。使用可选的start参数,从该位置开始测试。使用可选的end参数,在该位置停止比较。


如果我这样做,我的if语句会读取"If myString以 '芝加哥黑鹰队'或 '纽约游骑兵队'结尾,则打印'Success'"。这正确吗? - user5455038
2
@CalebRudnicki 的确。您可以这样做:if myStr.endswith(tuple(myList)): - Mazdak
这个答案真的应该被接受,尽管 OP 可能不再拥有账户。非常感谢您,它帮助了我!似乎你也可以直接在括号中插入元组,比如 word.endswith(('foo', 'bar')) - Lou

17

你可以使用关键字any

if any(myStr.endswith(s) for s in myList):
    print("Success")

这个答案可以更新为:myStr.endswith(tuple(myList)) - undefined

0
你可以这样做 :)
for i in myList:
    if myStr.endswith(i):
        print(myStr + " Ends with : " + i)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接