编写函数,接收一个字符串,分别统计大写字母、小写字母、数字、其他字符的个数,并以字典的形式返回结果。
时间: 2023-07-10 12:08:50 浏览: 53
可以使用 Python 的内置函数 `isupper()`、`islower()`和 `isdigit()` 来判断字符是大写字母、小写字母还是数字。其他字符可以使用 `isalpha()` 函数来判断,如果不是字母就是其他字符。
下面是实现这个功能的 Python 代码:
```python
def count_chars(string):
counts = {'upper': 0, 'lower': 0, 'digit': 0, 'other': 0}
for char in string:
if char.isupper():
counts['upper'] += 1
elif char.islower():
counts['lower'] += 1
elif char.isdigit():
counts['digit'] += 1
elif char.isalpha():
counts['other'] += 1
return counts
```
这个函数接收一个字符串作为参数,然后遍历字符串中的每个字符,根据字符的类型更新相应的计数器。最后将计数器以字典的形式返回。
相关问题
Python编写函数,接收一个字符串,分别统计大写字母、小写字母、数字、其他字符的个数,并以字典的形式返回结果。
可以使用Python内置的字符串方法isupper、islower、isdigit来判断字符的类别,然后使用字典来存储统计结果。以下是实现代码:
```python
def count_chars(s):
result = {'upper': 0, 'lower': 0, 'digit': 0, 'other': 0}
for char in s:
if char.isupper():
result['upper'] += 1
elif char.islower():
result['lower'] += 1
elif char.isdigit():
result['digit'] += 1
else:
result['other'] += 1
return result
```
其中,s为输入的字符串,result为统计结果的字典。在循环中,每遍历一个字符,就根据其类别更新对应的统计结果。最后返回结果字典即可。
python写代码 编写函数,接收一个字符串,分别统计大写字母、小写字母、数字、其他字符的个数,并以字典的形式返回结果
def count_chars(s):
"""
统计字符串中的大写字母、小写字母、数字、其他字符个数
:param s: 字符串
:return: 字典,包含各类字符个数
"""
count_dict = {'upper': 0, 'lower': 0, 'digit': 0, 'other': 0}
for char in s:
if char.isupper():
count_dict['upper'] += 1
elif char.islower():
count_dict['lower'] += 1
elif char.isdigit():
count_dict['digit'] += 1
else:
count_dict['other'] += 1
return count_dict