python统计不同字符个数。用户从键盘输入一行字符串, 编写一个程序,统计并输出其中英文、数字、空 格和其他字符的个数
时间: 2024-03-22 13:06:41 浏览: 77
可以使用Python的字符串方法和字符分类来统计不同字符的个数。下面是一个示例程序:
```python
def count_characters(string):
count_letters = 0
count_digits = 0
count_spaces = 0
count_others = 0
for char in string:
if char.isalpha():
count_letters += 1
elif char.isdigit():
count_digits += 1
elif char.isspace():
count_spaces += 1
else:
count_others += 1
return count_letters, count_digits, count_spaces, count_others
input_string = input("请输入一行字符串:")
letter_count, digit_count, space_count, other_count = count_characters(input_string)
print("英文字母个数:", letter_count)
print("数字个数:", digit_count)
print("空格个数:", space_count)
print("其他字符个数:", other_count)
```
这个程序定义了一个`count_characters`函数,它接受一个字符串作为参数,并返回英文字母、数字、空格和其他字符的个数。在主程序中,用户从键盘输入一行字符串,并调用`count_characters`函数进行统计并输出各个字符的个数。
阅读全文