python1.统计不同字符个数。用户从键盘输入一行字符,编写一个程序,统计并输出其中英文字符、数字、空格和其他字符的个数。
时间: 2024-06-15 18:07:44 浏览: 21
可以使用Python编写一个程序来实现统计不同字符个数的功能。以下是一个示例代码:
```python
def count_characters(input_string):
# 初始化计数器
count_letters = 0
count_digits = 0
count_spaces = 0
count_others = 0
# 遍历输入字符串的每个字符
for char in input_string:
# 判断字符类型并增加相应计数器的值
if char.isalpha():
count_letters += 1
elif char.isdigit():
count_digits += 1
elif char.isspace():
count_spaces += 1
else:
count_others += 1
# 输出结果
print("英文字符个数:", count_letters)
print("数字个数:", count_digits)
print("空格个数:", count_spaces)
print("其他字符个数:", count_others)
# 从键盘读取输入字符串
input_string = input("请输入一行字符:")
# 调用函数进行统计
count_characters(input_string)
```
运行以上代码,用户可以从键盘输入一行字符,程序将统计并输出其中英文字符、数字、空格和其他字符的个数。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)