Test a String for a Substring?

This question already has an answer here:

  • Does Python have a string 'contains' substring method? 13 answers

  • 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/9376.html

    上一篇: 如何找出一个字符串是否在Python的另一个字符串中?

    下一篇: 测试一个字符串的子字符串?