python - 计算较长字符串中子字符串出现次数的函数
问题描述
找到一个接受 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
这适用于区分大小写但不区分大小写。
解决方案
你几乎明白了;请注意,它.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
推荐阅读
- amazon-web-services - 解析 EC2 用户数据 cloudformation 模板中的动态引用
- splat - 当被 culam 解析时,如何在 NodeConstant.cpp 中找到未通过断言错误的代码?
- docker - 如果我启动 Node2,Cassndra Docker Image 会停止
- python - PySpark:导出到 SQL Server 时更改时间戳
- apache-camel - 在 Jboss Fuse 中运行 Spring Boot Camel
- list - 从 Haskell 列表中删除项目
- python - 数据库中的熊猫年数据转换为列中的年数
- html - 如何加粗标题html标签
- c# - .NET Core 程序集中的嵌入式资源命名
- python - 子图频率图