|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
练习题:编写一个函数,分别统计出传入字符串参数(可能不只一个参数)的英文字母、空格、数字和其它字符的个数。
- def count(*var):
- length = len(var)
- for j in range(length):
- number = 0
- letter = 0
- others = 0
- spaces = 0
- # 依次取出传入列表中的每个字符串进行参数判断
- for each in var[j]:
- if each.isalpha():
- letter += 1
- elif each.isdigit():
- number += 1
- elif each == ' ':
- spaces += 1
- else:
- others += 1
- print('第%d个字符串共有:英文字母%d个,数字%d个,空格%d个,其他字符%d个' % (j + 1, letter, number, spaces, others))
- ls = []
- x = int(input('请输入参数个数:'))
- # 将依次输入的字符串存放在列表中
- for i in range(x):
- ls.append(input('请输入第%d个参数:' % (i + 1)))
- i += 1
- count(ls)
复制代码 问题:
1.运行后只能输出第一个字符串的结果,之后的都无法输出
2.输出的结果不正确,不知道是我的if语句和print哪里用错了
试试这样:
- def count(*var):
- length = len(var)
- for j in range(length):
- number = 0
- letter = 0
- others = 0
- spaces = 0
- # 依次取出传入列表中的每个字符串进行参数判断
- for each in var[j]:
- if each.isalpha():
- letter += 1
- elif each.isdigit():
- number += 1
- elif each == ' ':
- spaces += 1
- else:
- others += 1
- print('第%d个字符串共有:英文字母%d个,数字%d个,空格%d个,其他字符%d个' % (j + 1, letter, number, spaces, others))
- ls = []
- x = int(input('请输入参数个数:'))
- # 将依次输入的字符串存放在列表中
- for i in range(x):
- ls.append(input('请输入第%d个参数:' % (i + 1)))
- i += 1
- count(*ls)
复制代码
|
|