Python判断一个字符串是否包含某个指定的字符串

CatherineC00 2020-01-17

成员操作符 in 

str = "string test string test"
    find1 = "str"
    find2 = "test"
    print(find1 in str)      # True
    print(find1 not in str)  # False

偷偷说一句:in不只是在字符串中可以使用哦!期待后面的教程叭

使用字符串对象的 find() 、 rfind() 、 index() 、rindex()、 count() 

str = "string test string test"
    find1 = "str"
    find2 = "test"
    # find
    print(str.find(find1))  # 0
    print(str.find(find2))  # 7

    # rfind
    print(str.rfind(find1))  # 12
    print(str.rfind(find2))  # 19

    # index
    print(str.index(find1))  # 0
    print(str.index(find2))  # 7

    # rindex
    print(str.rindex(find1))  # 12
    print(str.rindex(find2))  # 19

    # count
    print(str.count(find1))  # 2
    print(str.count(find2))  # 2

相关推荐