网站建设资讯

NEWS

网站建设资讯

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

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

我们提供的服务有:网站建设、成都做网站、微信公众号开发、网站优化、网站认证、海口ssl等。为上千多家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的海口网站制作公司

一、提出问题

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

二、难点提示

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

循环遍历字符串

  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)
使用Python统计字符串中各种字符的个数

本文标题:使用Python统计字符串中各种字符的个数
标题URL:http://cdweb.net/article/pjghio.html