Python 字符串中查找子串出现次数:count() 方法
可以使用字符串的 'count()' 方法来实现查找给定子串在一个字符串中出现的次数。该方法返回给定子串在字符串中出现的次数。
例如,以下代码计算字符串 'hello world' 中子串 'l' 的出现次数:
s = 'hello world'
sub = 'l'
count = s.count(sub)
print(count) # 输出 3
如果要忽略大小写,则可以先将字符串和子串都转换为小写或大写,再调用 'count()' 方法。例如:
s = 'Hello World'
sub = 'l'
count = s.lower().count(sub.lower())
print(count) # 输出 3
原文地址: https://www.cveoy.top/t/topic/nqJ0 著作权归作者所有。请勿转载和采集!