统计不同字符个数用户从键盘输入一行字符编写一个程序统计并输出其中英文字符数字空格和其他字符的个数
时间: 2023-10-28 21:17:09 浏览: 83
```python
s = input("请输入一行字符:")
letters = 0
digits = 0
spaces = 0
others = 0
for c in s:
if c.isalpha(): # 判断是否为英文字母
letters += 1
elif c.isdigit(): # 判断是否为数字
digits += 1
elif c.isspace(): # 判断是否为空格
spaces += 1
else: # 其他字符
others += 1
print("英文字母个数:", letters)
print("数字个数:", digits)
print("空格个数:", spaces)
print("其他字符个数:", others)
```
输入示例:
```
请输入一行字符:Hello, 123 world!
```
输出示例:
```
英文字母个数: 10
数字个数: 3
空格个数: 2
其他字符个数: 2
```
相关问题
统计不同字符个数。用户从键盘输入一行字符,编写一个程序,统计并输出其中英文字符、数字、空格和其他字符
以下是一个用Python编写的程序,用于统计用户输入的一行字符中英文字符、数字、空格和其他字符的个数:
```python
def count_characters(input_string):
# 初始化计数器
english_count = 0
digit_count = 0
space_count = 0
other_count = 0
# 遍历输入的字符串
for char in input_string:
if char.isalpha(): # 判断是否为英文字符
english_count += 1
elif char.isdigit(): # 判断是否为数字
digit_count += 1
elif char.isspace(): # 判断是否为空格
space_count += 1
else: # 其他字符
other_count += 1
# 输出结果
print(f"英文字符个数: {english_count}")
print(f"数字个数: {digit_count}")
print(f"空格个数: {space_count}")
print(f"其他字符个数: {other_count}")
# 获取用户输入
user_input = input("请输入一行字符: ")
# 调用函数进行统计
count_characters(user_input)
```
这个程序的工作原理如下:
1. 定义了一个函数 `count_characters` 来处理字符统计。
2. 初始化了四个计数器,分别用于统计英文字符、数字、空格和其他字符。
3. 使用 for 循环遍历输入的字符串。
4. 使用字符串方法 `isalpha()`, `isdigit()`, 和 `isspace()` 来判断字符的类别。
5. 根据判断结果增加相应的计数器。
6. 最后,输出统计结果。
使用这个程序,用户可以输入一行字符,程序将统计并显示其中英文字符、数字、空格和其他字符的个数。
用户从键盘输入一行字符。请编写一个程序,统计并输出其中英文字符、数字符号、空格和其他字符的个数
这个程序的功能是统计用户从键盘输入的一行字符中英文字符、数字符号、空格和其他字符的个数。程序使用了 for 循环和 if 语句来遍历输入的字符并进行分类统计。具体实现方法如下:
1. 定义四个变量 letter、number、Space 和 character,分别表示英文字符、数字符号、空格和其他字符的个数,初始值都为 0。
2. 使用 for 循环遍历输入的字符,对于每个字符,使用 if 语句进行分类统计。如果是英文字符,将 letter 变量加 1;如果是数字,将 number 变量加 1;如果是空格,将 Space 变量加 1;否则将 character 变量加 1。
3. 统计完成后,使用 print 函数输出各个分类的字符个数。
下面是代码实现:
```
s = input("请输入一行字符:")
letter = 0 #字母
Space = 0 #空格
number = 0 #数字
character = 0 #其他字符
for i in s:
if ord("a") <= ord(i.lower()) <= ord("z"):
letter += 1
elif ord(" ") == ord(i):
Space += 1
elif ord("0") <= ord(i) <= ord("9"):
number += 1
else:
character += 1
print("英文个数:" + str(letter))
print("空格个数:" + str(Space))
print("数字个数:" + str(number))
print("其他字符个数:" + str(character))
```
阅读全文
相关推荐















