【问题标题】:Test a string for a substring [duplicate]测试子字符串的字符串[重复]
【发布时间】:2011-07-25 06:52:59
【问题描述】:

是否有一种简单的方法可以测试 Python 字符串“xxxxABCDyyyy”以查看其中是否包含“ABCD”?

【问题讨论】:

    标签: python string


    【解决方案1】:
    if "ABCD" in "xxxxABCDyyyy":
        # whatever
    

    【讨论】:

    • 这适用于此处,但如果您针对非字符串进行测试,则可能无法给出预期结果。例如。如果针对字符串列表进行测试(可能使用if "ABCD" in ["xxxxabcdyyyy"]),这可能会静默失败。
    • @GreenMatt 如果你知道这是一个列表,就说if 'ABCD' in list[0]
    【解决方案2】:

    除了使用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
    

    【讨论】:

    • 最后一个需要和re.escape在一般情况下调用。
    猜你喜欢
    • 1970-01-01
    • 2015-11-12
    • 2017-12-29
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    • 2017-02-15
    • 2014-11-05
    • 2022-01-07
    相关资源
    最近更新 更多