Python count()方法

描述

Python count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。

语法

count()方法语法:

str.count(sub, start= 0,end=len(string))

参数

  • sub -- 搜索的子字符串
  • start -- 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
  • end -- 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。

返回值

该方法返回子字符串在字符串中出现的次数。

Python List count()方法

描述

count() 方法用于统计某个元素在列表中出现的次数。

语法

count()方法语法:

list.count(obj)

参数

  • obj -- 列表中统计的对象。

返回值

返回元素在列表中出现的次数。

 

# -*- coding:utf-8-*-

# 方法一:统计单个字符出现次数
def str_count_one(strs:str, find_str:str):
    return strs.count(find_str)

# 方法二:实现统计字符串中每个字符出现的次数
def str_count_two(strs:str):
    #1、目标字符串转为列表
    strs_list = list(strs)
    #2、用一个列表记录总共有多少种字符
    new_str_list = []

    for i in strs_list:
        if i not in new_str_list:
            new_str_list.append(i)

    print('new_str_list:%s' % new_str_list)
    #3.用一个字典记录结果,遍历列表,求count()
    d = {}

    for i in new_str_list:
        d[i] = strs_list.count(i)
    print(d)

# 方法三:统计全部字符出现次数
def str_count_three(strs:str):
    from collections import Counter
    return Counter(strs)

if __name__ == '__main__':
    # xx = str_count_one('sfdsfdsf', 's')
    # yy = str_count_two('sfdsfdsf')
    zz = str_count_three('sfdsfdsf')
    # print(xx)
    # print(yy)
    print(zz)

 

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐