3.设计一个函数,计算传入字符串中数字、字母、空格以及其他字符的个数。
时间: 2024-05-12 07:20:47 浏览: 86
```python
def count_chars(string):
letter_count = 0
digit_count = 0
space_count = 0
other_count = 0
for char in string:
if char.isalpha():
letter_count += 1
elif char.isdigit():
digit_count += 1
elif char.isspace():
space_count += 1
else:
other_count += 1
return letter_count, digit_count, space_count, other_count
```
使用示例:
```python
string = "Hello World! 123"
letter_count, digit_count, space_count, other_count = count_chars(string)
print("字母数:", letter_count)
print("数字数:", digit_count)
print("空格数:", space_count)
print("其他字符数:", other_count)
```
输出结果:
```
字母数: 10
数字数: 3
空格数: 2
其他字符数: 1
```
阅读全文