python学习-写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数

题目:

  写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数

思路:

  1、分别定义统计【数字】、【字母】、【空格] 以及 【其他】的变量,并初始化为0

  2、遍历传入的字符串,判断字符串内各字符的类型,并分别累加

  3、输出结果

代码实现:

  

 1 def count_str(strs):
 2     """计算字符串中数字,字母,空格及其他的个数"""
 3     #  【数字】、【字母】、【空格] 以及 【其他】初始化个数
 4     int_count,str_count,spa_count,other_count = 0,0,0,0
 5     for i in strs:     #  遍历字符串
 6         if i.isdigit():   # 判断是否为数字
 7             int_count += 1
 8         elif i.isalnum():   # 判断是否为字母
 9             str_count += 1
10         elif i.isspace():   # 判断是否为空格
11             spa_count += 1
12         else:
13             other_count +=1
14     # 最后输出
15     print("字符串s中,数字个数={},字母个数={},空格个数={},其他个数={}".format(int_count,str_count,spa_count,other_count))
16 
17 if __name__ == "__main__":
18     strs = input("请输入字符串s:")
19     count_str(strs)   # 调用函数

 

学习没有捷径,需要日积月累的积淀及对技术的热爱。
原文地址:https://www.cnblogs.com/laizhenghua/p/12341118.html