编写一个程序,统计字符串中英文字母、空格、数字和其他字母的个数。
时间: 2023-11-17 11:16:06 浏览: 53
好的,以下是一个 Python 的实现示例:
```python
def count_chars(s):
counts = {"alphabet": 0, "space": 0, "digit": 0, "other": 0}
for c in s:
if c.isalpha():
counts["alphabet"] += 1
elif c.isspace():
counts["space"] += 1
elif c.isdigit():
counts["digit"] += 1
else:
counts["other"] += 1
return counts
s = "Hello World! 123"
counts = count_chars(s)
print("Alphabets:", counts["alphabet"])
print("Spaces:", counts["space"])
print("Digits:", counts["digit"])
print("Others:", counts["other"])
```
这个程序首先定义一个字典 `counts`,用于记录各种字符的数量,然后遍历字符串 `s` 中的每个字符,根据字符的类型将对应的计数器加一,最后返回计数器的值。你可以尝试输入不同的字符串进行测试。
相关问题
编写python程序实现从用户输入一个字符串,分别统计该字符串中英文字母、数字、空格和其他字符的个数。
好的,这个问题很简单,以下是Python代码实现:
```python
string = input("请输入一个字符串:")
letters = 0
digits = 0
spaces = 0
others = 0
for char in string:
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)
```
希望这能帮到你!
编写程序,输入一串字符,分别统计其中的英文字母、空格、数字和其他字符的个数
python
# 统计字符中的英文字母、空格、数字和其他字符的个数
string = input("请输入一串字符:")
letters = 0
spaces = 0
digits = 0
others = 0
for i in string:
if i.isalpha():
letters += 1
elif i.isspace():
spaces += 1
elif i.isdigit():
digits += 1
else:
others += 1
print("英文字母个数为:", letters)
print("空格个数为:", spaces)
print("数字个数为:", digits)
print("其他字符个数为:", others)
```
--相关问题--: