用两种方法输出子串的所有位置

一、用find输出子串的所有位置

程序

# -*- coding: utf-8 -*-
'''
功能:用find输出子串的所有位置
作者:雾爱
日期:2021年11月29日
'''
at_str = '@熊大@熊二@光头@老板'
pos = at_str.find('@')
count = 0
while pos != -1:
    count =count + 1
    print('@出现的位置:{}'.format(pos))
    pos = at_str.find('@',pos+1)
print('@总共出现了{}次'.format(count))

程序结果

在这里插入图片描述

二、用index输出子串所有的位置

程序

# -*- coding: utf-8 -*-
'''
功能:用index输出子串的所有位置
作者:雾爱
日期:2021年11月29日
'''
at_str = '@熊大@熊二@光头@老板'
pos = at_str.index('@')
count = 0
try:
    while pos != -1:
        count =count + 1
        print('@出现的位置:{}'.format(pos))
        pos = at_str.index('@',pos+1)
except ValueError:
    pass
print('@总共出现了{}次'.format(count))

程序结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_62491692/article/details/121643273