统计字符串中字母、数字、空格和其他字符的个数
时间: 2023-03-25 21:05:04 浏览: 105
可以通过遍历字符串,对每个字符判断其类型,然后统计相应的计数器。
例如:
```
def count_chars(s):
letter_count = 0
digit_count = 0
space_count = 0
other_count = 0
for c in s:
if c.isalpha():
letter_count += 1
elif c.isdigit():
digit_count += 1
elif c.isspace():
space_count += 1
else:
other_count += 1
return letter_count, digit_count, space_count, other_count
```
阅读全文