测试一个字符串的子字符串?

这个问题在这里已经有了答案:

  • Python是否有一个字符串'contains'substring方法? 13个答案

  • if "ABCD" in "xxxxABCDyyyy":
        # whatever
    

    除了使用“in”运算符(最简单)之外,还有其他几种方法

    index()

    >>> try :
    ...   "xxxxABCDyyyy".index("test")
    ... except ValueError:
    ...   print "not found"
    ... else:
    ...   print "found"
    ...
    not found
    

    find()

    >>> if "xxxxABCDyyyy".find("ABCD") != -1:
    ...   print "found"
    ...
    found
    

    re

    >>> import re
    >>> if re.search("ABCD" , "xxxxABCDyyyy"):
    ...  print "found"
    ...
    found
    
    链接地址: http://www.djcxy.com/p/9375.html

    上一篇: Test a String for a Substring?

    下一篇: What does a "Cannot find symbol" compilation error mean?