1统计字符串中的字符个数。(4分)
题目内容:
定义函数countchar()统计字符串中所有出现的字母的个数(允许输入大写字符,并且计数时不区分大小写)。
输入格式:
字符串
输出格式:
列表
输入样例:
Hello, World!
输出样例:
题目内容:
定义函数countchar()统计字符串中所有出现的字母的个数(允许输入大写字符,并且计数时不区分大小写)。
输入格式:
字符串
输出格式:
列表
输入样例:
Hello, World!
输出样例:
[0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 3, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0]
<span style="font-size:14px;">>>> def countchar(a):
l = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
b = list(a.lower())
c = []
for i in l:
m = b.count(i)
c.append(m)
return c
>>> countchar('Hello,World!')
[0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 3, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0]</span>
<span style="font-size:14px;">>>> def countchar(a): #非原创
char=a.lower()
count=[0]*26
for i in list(char):
if 97<=ord(i)<=122: #ord():返回单字符在ASCII中对应的整数。在此表示a~z
count[ord(i)-97]+=1
else:
continue
return count
>>> countchar('Hello,World!')
[0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 3, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0]</span>