带多个字符串的Python endswith()

2024-06-28 19:23:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一根绳子:

myStr = "Chicago Blackhawks vs. New York Rangers"

我还有一个清单:

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

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

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

Tags: newif语句vsmapleyork绳子chicago
3条回答

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

>>> myStr = "Chicago Blackhawks vs. New York Rangers"
>>> 
>>> my_suffixes = ("Toronto Maple Leafs", "New York Rangers")
>>> 
>>> myStr.endswith(my_suffixes)
True

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

Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.

你可以这样做:)

for i in myList:
    if myStr.endswith(i):
        print(myStr + " Ends with : " + i)

您可以使用关键字any

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

相关问题 更多 >