功能实现:

***利用python实现统计一个字符串中数字、字母及其他字符的个数和各个字符的总数。


方法一:

***利用 isdigit() isalpha()函数判断字符是否是数字或者字母。

代码如下:

s = input("请输入一串字符: ")
num, char, space, other = 0, 0, 0, 0      #分别统计数字、字母、空格、其他字符个数
for i in s:
    #是否为数字
    if i.isdigit():
        num += 1
    #是否为字母
    elif i.isalpha():
        char += 1
    elif i == ' ':
        space += 1
    else:
        other += 1
print(num, char, space, other)

输出结果:

方法二:

***使用内置函数str.count()统计各个字符的总数。

代码如下:

str = input()
resoult = {}
for i in str:
    resoult[i] = str.count(i)
print(resoult)

输出结果:

更多推荐

【python基础】:分类统计各字符的个数