python怎么统计字符串出现的次数

avatar
作者
猴君
阅读量:0

可以使用count()方法来统计字符串中子串出现的次数。count()方法接受一个子串作为参数,并返回子串在字符串中出现的次数。

例如,统计字符串"apple"中字母p出现的次数:

s = "apple" count = s.count("p") print(count)  # 输出: 2 

另外,如果要统计字符串中多个子串同时出现的次数,可以使用循环遍历的方式来实现:

s = "apple" substrings = ["p", "e"] counts = [s.count(substring) for substring in substrings] print(counts)  # 输出: [2, 2] 

这样,counts列表中的每个元素分别表示对应子串在字符串中出现的次数。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!