判斷字符串中是否有某個子串 這裏有六個方法 不使用string模塊
1.in
存在則輸出TRUE 不存在則輸出FALSE
a = 'love you'
b = 'you'
c = 'no'
print(b in a) #True
print(c in a) #False
2.find()
從左向右查找子串 存在則輸出子串首字符的索引值 不存在則輸出-1
a = 'love you'
b = 'you'
c = 'no'
print(a.find(b)) #5
print(a.find(c)) #-1
3.rfind()
從左向右查找子串 存在則輸出子串首字符的索引值 不存在則輸出-1(從右向左查找 從後面找到的第一個子串位置)
a = 'love you'
b = 'you'
c = 'no'
print(a.rfind(b)) #5
print(a.rfind(c)) #-1
4.index()
從左向右查找子串 存在則輸出子串首字符的索引值 不存在則報錯 要確定子串存在於母串中
a = 'love you'
b = 'you'
c = 'no'
print(a.index(b)) #5
print(a.index(c)) #報錯
5.rindex()
從右向左查找子串 存在則輸出子串首字符的索引值 不存在則報錯 要確定子串存在於母串中(從右向左查找 從後面找到的第一個子串位置)
a = 'love you'
b = 'you'
c = 'no'
print(a.rindex(b)) #5
print(a.rindex(c)) #報錯
6.count()
計數母字符串中含有多少個子串
a = 'love you do you love me'
b = 'you'
c = 'no'
print(a.count(b)) #2
print(a.count(c)) #0