【问题标题】:Python endswith() with multiple stringPython endwith() 带有多个字符串
【发布时间】:2016-06-01 08:23:42
【问题描述】:

我有一个字符串:

myStr = "Chicago Blackhawks vs. New York Rangers"

我还有一个清单:

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

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

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

【问题讨论】:

    标签: python python-3.x python-2.7 ends-with


    【解决方案1】:

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

    【讨论】:

    • 如果我这样做,我的 if 语句将显示“如果 myString 以 'Chicago Blackhawks' 或 'New York Rangers' 结尾,则打印 'Success'”。这是正确的吗?
    • @CalebRudnicki 确实如此。你可以if myStr.endswith(tuple(myList)):
    • 这个答案确实应该被接受,尽管 OP 可能不再有帐户了。不过谢谢你,它帮助了我!看来您也可以将元组直接插入括号中,例如word.endswith(('foo', 'bar'))
    【解决方案2】:

    你可以使用关键字any

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

    【讨论】:

      【解决方案3】:

      你可以这样做:)

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

      【讨论】:

        猜你喜欢
        • 2014-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-23
        • 1970-01-01
        • 2014-06-23
        • 2020-08-14
        相关资源
        最近更新 更多