3. 统计不同字符个数。编写一个程序,接受用户从键盘输入一行字符,统计并输出其中英文字符、数字、空格和其他字符的个数。
时间: 2023-10-28 21:19:25 浏览: 12
```python
s = input("请输入一行字符:")
eng_cnt = 0
num_cnt = 0
space_cnt = 0
other_cnt = 0
for c in s:
if c.isalpha():
eng_cnt += 1
elif c.isdigit():
num_cnt += 1
elif c.isspace():
space_cnt += 1
else:
other_cnt += 1
print("英文字符个数:", eng_cnt)
print("数字个数:", num_cnt)
print("空格个数:", space_cnt)
print("其他字符个数:", other_cnt)
```
示例输出:
```
请输入一行字符:Hello, 123! World.
英文字符个数: 11
数字个数: 3
空格个数: 3
其他字符个数: 2
```
相关问题
3.统计不同字符个数。编写一个Python程序,接受用户从键盘输入一行字符,统计并输出其中英文字符、数字、空格和其他字符的个数。
```
line = input("请输入一行字符:")
letters = 0
digits = 0
spaces = 0
others = 0
for char in line:
if char.isalpha():
letters += 1
elif char.isdigit():
digits += 1
elif char.isspace():
spaces += 1
else:
others += 1
print("英文字符个数为:", letters)
print("数字个数为:", digits)
print("空格个数为:", spaces)
print("其他字符个数为:", others)
```
示例输出:
```
请输入一行字符:Hello, World! 123
英文字符个数为: 11
数字个数为: 3
空格个数为: 2
其他字符个数为: 1
```
python1.统计不同字符个数。用户从键盘输入一行字符,编写一个程序,统计并输出其中英文字符、数字、空格和其他字符的个数。
可以使用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)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)