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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM