使用 Python 的 s.find() 方法循环遍历查找子串出现次数时,如果子串出现在字符串的首尾位置,可能会导致统计次数错误。这是因为 s.find() 方法只会返回子串第一次出现的位置,而不会重复计算。

例如,对于字符串 s='hello world, world is beautiful',要查找子串 'world' 出现的次数,可以使用以下代码:

count = 0
pos = s.find('world')
while pos != -1:
    count += 1
    pos = s.find('world', pos+1)
print(count)

这段代码会输出 2,即子串 'world' 在字符串 s 中出现了 2 次。

但是,如果子串出现在字符串 s 的首尾位置,例如 s='world is beautiful, hello world',则上述代码会输出 1,而实际上子串 'world's 中出现了 2 次。

为了解决这个问题,可以在循环遍历时判断子串是否出现在首尾位置,如果是,则特殊处理。例如:

count = 0
pos = s.find('world')
while pos != -1:
    count += 1
    if pos == 0:
        pos = s.find('world', pos+1)
    elif pos == len(s)-len('world'):
        break
    else:
        pos = s.find('world', pos+1)
print(count)

这段代码会输出 2,正确地统计了子串 'world's 中出现的次数。

Python 字符串查找子串出现次数:s.find() 方法的局限性及解决方法

原文地址: https://www.cveoy.top/t/topic/nqKG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录