用python编写函数,接收一个字符串,分别统计大写字母、小写字母、数字、其他字符的个数,并以元组的形式返回结果。
时间: 2023-06-19 11:03:10 浏览: 517
可以使用Python中的字符串函数和循环来实现这个函数。以下是一个实现示例:
```python
def count_chars(string):
uppercase = 0
lowercase = 0
digits = 0
other = 0
for char in string:
if char.isupper():
uppercase += 1
elif char.islower():
lowercase += 1
elif char.isdigit():
digits += 1
else:
other += 1
return (uppercase, lowercase, digits, other)
```
这个函数接收一个字符串参数 `string`,然后使用循环遍历字符串中的每个字符。对于每个字符,使用字符串方法 `isupper()`、`islower()` 和 `isdigit()` 来判断它是否为大写字母、小写字母或数字,并相应地增加计数器。如果字符不属于这三个类别,则将其计入 "其他字符" 的计数器。最后,将计数器的值作为元组返回。
可以使用以下代码测试这个函数:
```python
string = "Hello, World! 123"
counts = count_chars(string)
print(counts)
```
这将输出 `(2, 8, 3, 5)`,表示字符串中有 2 个大写字母、8 个小写字母、3 个数字和 5 个其他字符。