Python输出子串的所有位置

"""
"""
功能:输出子串的所有位置
作者:cxf
日期:20211125"""
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))
# 直接用count()函数来获取子串出现的位置
print('@总共出现了{}次'.format(at_str.count('@')))

在这里插入图片描述
用到了异常处理

"""
功能:输出子串的所有位置使用index()函数查找
作者:cxf
日期:2021年11月25日
"""
at_str = '@娃哈哈 @萌萌哒 @小机灵 @小宝宝'
pos = at_str.index('@')
count = 0
try:
    while True:
        count = count + 1
        print('@出现位置:{}'.format(pos))
        pos = at_str.index('@', pos + 1)
except ValueError:
    pass
print('@总共出现{}次。'.format(count))
# 直接用count()函数来获取子串出现的位置
print('@总共出现了{}次'.format(at_str.count('@')))

在这里插入图片描述

おすすめ

転載: blog.csdn.net/qq_62590351/article/details/121541642