首页 > 解决方案 > 计算较长字符串中子字符串出现次数的函数

问题描述

找到一个接受 3 个参数的函数:基本字符串、要在基本字符串中搜索的子字符串和一个布尔参数来判断它是不区分大小写(默认,true)还是区分大小写(false)。返回找到子字符串的次数。除了upper()和lower()之外没有额外的进口,到目前为止我有:

def count_substring(base, sub, case_default=True):

length = len(sub)
times = 0

if case_default == False:
    for i in range(len(base)-len(sub)+1):
        if (base[i:i+len(sub)] == sub):
            times +=1
else:
    base.lower()
    sub.lower()
    for i in range(len(base)-len(sub)+1):
        if (base[i:i+len(sub)] == sub):
            times +=1

return times 

这适用于区分大小写但不区分大小写。

标签: pythonsubstringcase-sensitivecase-insensitive

解决方案


你几乎明白了;请注意,它.lower()返回一个新字符串,而不是就地修改字符串!

def count_substring(base, sub, case_insensitive=True):
    times = 0
    if case_insensitive:
        base = base.lower()
        sub = sub.lower()

    for i in range(len(base)-len(sub)+1):
        if (base[i:i+len(sub)] == sub):
            times += 1

    return times

一个更简单的解决方案可能是使用split,它是其中的一部分,str因此不需要导入:

def count_substring(base, sub, case_insensitive=True):
    if case_insensitive:
        base = base.lower()
        sub = sub.lower()
    return len(base.split(sub)) - 1

推荐阅读