4.2.统计不同字符个数。用户从键盘输入行字符,编写个程序, 统计并输出其中英文字符、数字、空格和其他字符的个数。
时间: 2024-03-22 08:30:40 浏览: 22
下面是一个统计不同字符个数的 Python 代码:
```python
text = input("请输入一行字符:")
letters = 0
digits = 0
spaces = 0
others = 0
for char in text:
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, 123 world!
英文字符个数: 11
数字个数: 3
空格个数: 2
其他字符个数: 1
```
相关问题
统计不同字符个数用户从键盘输入一行字符编写一个程序统计并输出其中英文字符数字空格和其他字符的个数
好的,以下是 Python 的代码实现:
```python
str = input("请输入一行字符:")
letter = 0
digit = 0
space = 0
other = 0
for i in str:
if i.isalpha(): # 判断是否为字母
letter += 1
elif i.isdigit(): # 判断是否为数字
digit += 1
elif i.isspace(): # 判断是否为空格
space += 1
else:
other += 1
print("英文字母个数:", letter)
print("数字个数:", digit)
print("空格个数:", space)
print("其他字符个数:", other)
```
程序首先提示用户输入一行字符,然后利用 for 循环遍历字符串中的每个字符,判断其类型并进行计数,最后输出不同类型的字符个数即可。
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)
```
运行以上代码,用户可以从键盘输入一行字符,程序将统计并输出其中英文字符、数字、空格和其他字符的个数。
相关推荐
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.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)