任意输入一行字符,分别统计字母、数字、空格和其它字符的个数。
时间: 2023-11-22 11:55:37 浏览: 25
下面是一个 Python 的实现示例:
```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, ChitChat! 123
字母个数: 13
数字个数: 3
空格个数: 2
其它字符个数: 2
```
相关问题
输入一行字符分别统计英文字母空格数字和其他字符的个数
好的,以下是Python代码实现:
```
str = input("请输入一行字符:")
letters = 0
space = 0
digit = 0
others = 0
for i in str:
if i.isalpha():
letters += 1
elif i.isspace():
space += 1
elif i.isdigit():
digit += 1
else:
others += 1
print("英文字母个数为:", letters)
print("空格个数为:", space)
print("数字个数为:", digit)
print("其他字符个数为:", others)
```
输入一行字符后,程序会遍历每个字符,逐个判断其属于哪一类字符,并累加计数。最后输出各类字符的个数。
任意输入一行字符,分别统计字母、数字、空格和其它字符的个数
好的,我可以帮你实现这个功能。以下是 Python 代码示例:
```python
line = input("请输入一行字符:") # 获取用户输入的一行字符
letter_count = 0 # 字母个数
digit_count = 0 # 数字个数
space_count = 0 # 空格个数
other_count = 0 # 其他字符个数
for char in line:
if char.isalpha(): # 判断字符是否为字母
letter_count += 1
elif char.isdigit(): # 判断字符是否为数字
digit_count += 1
elif char.isspace(): # 判断字符是否为空格
space_count += 1
else:
other_count += 1 # 其他字符
# 打印统计结果
print("字母个数:", letter_count)
print("数字个数:", digit_count)
print("空格个数:", space_count)
print("其他字符个数:", other_count)
```
你可以将以上代码保存为一个 `.py` 文件并执行,输入一行字符后,即可得到统计结果。