要求:输入一个字符串,统计字符串中大写字母,小写字母,数字,其它字符的个数。
程序分析:
1. 初始化各种字符的计数器。
2. 遍历字符串的每个字符。
3. 对于每个字符,检查它是否为英文字母、空格、数字或其它字符。
4. 如果是英文字母,增加英文字母计数器。
5. 如果是空格,增加空格计数器。
6. 如果是数字,增加数字计数器。
7. 如果是其它字符,增加其它字符计数器。
8. 返回所有字符的计数器值。
以下是一个简单的Python代码来实现这个功能:
#!/usr/bin/python
#coding:utf-8
#author:菜就多练呀
def count_chars(s):
# 初始化计数器
upper_case_letters = 0
lower_case_letters = 0
spaces = 0
digits = 0
others = 0
# 遍历字符串
for char in s:
if char.isupper(): # 判断是否为大写字母
upper_case_letters += 1
elif char.islower(): # 判断是否为小写字母
lower_case_letters += 1
elif char.isspace(): # 判断是否为空格
spaces += 1
elif char.isdigit(): # 判断是否为数字
digits += 1
else: # 其它字符
others += 1
return {
"大写字母": upper_case_letters,
"小写字母": lower_case_letters,
"空格": spaces,
"数字": digits,
"其他": others
}
# 测试函数
test_str = input('请输入一个字符串:\n')#Hello World! 123
print(count_chars(test_str))#{'大写字母': 2, '小写字母': 8, '空格': 2, '数字': 3, '其他': 1}