Python判断字符串包含子字符串(个数、索引、全部位置)

从左向右查找子串,存在则输出子串首字符的索引值,不存在则输出-1

# find()

a = 'love you'
b = 'you'
c = 'no'
print(a.find(b)) #5
print(a.find(c)) #-1

从左向右查找子串,存在则输出子串首字符的索引值,不存在则输出-1

# rfind()

a = 'love you'
b = 'you'
c = 'no'
print(a.rfind(b)) #5
print(a.rfind(c)) #-1

计数母字符串中含有多少个子字符串

# count()

a = 'love you do you love me'
b = 'you'
c = 'no'
print(a.count(b)) #2
print(a.count(c)) #0

查找指定字符串包含子字符串全部位置,以列表形式返回

def indexstr(str1,str2):
    '''查找指定字符串str1包含指定子字符串str2的全部位置,以列表形式返回'''
    lenth2=len(str2)
    lenth1=len(str1)
    indexstr2=[]
    i=0
    while str2 in str1[i:]:
        indextmp = str1.index(str2, i, lenth1)
        indexstr2.append(indextmp)
        i = (indextmp + lenth2)
    return indexstr2

猜你喜欢

转载自blog.csdn.net/u012206617/article/details/126143217
今日推荐