练习题2:统计字符串中str='abdf1234'字母的个数
提示:Python循环采用
for i in range(4),那么i依次为0,1,2,3函数语法
range(start,stop[, step])
参数说明:
start:计数从start开始。默认是从0开始。例range (5)等价于range (0,5);
stop:计数到stop结束,但不包括stop。例如: range (0,5)是[0,1,2,3,4]没有5step:步长,默认为1。例如: range (0. 5)等价于range(0,5,1)
count=0
s='advsd123asd'
for i in range(len(s)):
if (s[i] >= 'a' and s[i] <= 'z') or (s[i] >= 'A' and s[i] <= 'Z'):
count+=1
print(count)
a='abcd1234'
count = 0
for i in range(len(a)):
if a[i].isalpha():
count+=1
print(count)
# 统计一个字符串中字母、数字及其他字符的个数,返回一个元组
def tongji(s):
count1 = 0
count2 = 0
count3 = 0
for i in range(len(s)):
if (s[i] >= 'a' and s[i] <= 'z') or (s[i] >= 'A' and s[i] <= 'Z'):
count1 = count1 + 1
elif (s[i] >= '0' and s[i] <= '9'):
count2 = count2 + 1
else:
count3 = count3 + 1
return (count1,count2,count3)
s = input("请输入一个字符串:")
print(tongji(s))