用python编写函数,接收一个字符串,分别统计大写字母、小写字母、数字、其他字符的个数,并以元组的形式返回结果
时间: 2024-06-09 09:07:19 浏览: 14
可以使用 Python 的内置函数 `isupper()`、`islower()`、`isdigit()` 来判断字符是大写字母、小写字母还是数字。其他字符则可以用 ASCII 码进行判断。下面是一个实现样例:
```python
def count_chars(s):
upper_count = 0
lower_count = 0
digit_count = 0
other_count = 0
for c in s:
if c.isupper():
upper_count += 1
elif c.islower():
lower_count += 1
elif c.isdigit():
digit_count += 1
else:
other_count += 1
return (upper_count, lower_count, digit_count, other_count)
```
这个函数接受一个字符串 `s`,并通过遍历字符串中的每个字符进行统计。最后将结果以元组的形式返回。你可以按照下面的方式调用该函数:
```python
result = count_chars('Hello, World! 123')
print(result)
```
输出结果为:
```
(2, 8, 3, 3)
```
其中,大写字母有 2 个,小写字母有 8 个,数字有 3 个,其他字符有 3 个。