Python3: 对两个字符串进行匹配

Python里一共有三种字符串匹配方式,用于判断一个字符串是否包含另一个字符串。比如判断字符串“HelloWorld”中是否包含“World”:

def stringCompare(str1, str2):
    if str1 in str2:
        print("yes1")


# index指str2在str1中的开始下标,为-1则证明str1中不包含str2
def stringCompare2(str1, str2):
    if str1.index(str2) > -1:
        print("yes2")


# 同样是查询str2在str1中的开始下标
def stringCompare3(str1, str2):
    if str1.find(str2) > -1:
        print("yes3")


if __name__ == '__main__':
    a = "helloworld"
    b = "world"
    stringCompare(b, a)
    stringCompare2(a, b)
    stringCompare3(a, b)

 

posted @ 2017-12-06 20:20  一只敲码的猫  阅读(19451)  评论(0编辑  收藏  举报