gpt4 book ai didi

Python endswith() 带有多个字符串

转载 作者:太空狗 更新时间:2023-10-29 17:54:11 26 4
gpt4 key购买 nike

我有一个字符串:

myStr = "Chicago Blackhawks vs. New York Rangers"

我还有一个列表:

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

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

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

最佳答案

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]])

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. Withoptional end, stop comparing at that position.

关于Python endswith() 带有多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35510787/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com