使用Python统计字符串中各种字符的个数

Python 统计字符串中各种字符出现的次数

一、提出问题

随机输入一段字符串,包括数字,英文,空格,其他字符,统计这些字符在其中出现的次数

二、难点提示

思路:从键盘随机输入一段字符串,然后循环遍历字符串,通过循环字符串中的每一个字符,统计各类字符出现的次数

使用Python统计字符串中各种字符的个数

循环遍历字符串

  1. 判断数字字符 —— 使用: isdigit() 方法
  2. 判断空格 —— 使用: isspace() 方法
  3. 判断英文单词 —— 使用 isalpha() 方法

三、代码实现

#求字符串中的各种字符个数, 数字,英文单词,空格,特殊字符def count(str):    num_number=char_number=space_number=other_number=0    for i in str:        if i.isdigit():#判断数字            num_number+=1        elif i.isspace():#判断空格             space_number+=1        elif i.isalpha():#判断英文单词            char_number+=1        else:            other_number+=1    print("英文字符有:{} 数字字符有:{} 空格有:{} 特殊字符有:{}".format(char_number,num_number,space_number,other_number))if __name__ == '__main__':    s = "123dsse  ,../n"    count(s)
发布了222 篇原创文章 · 获赞 185 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qfluohao/article/details/103961947