编写生成器函数,接收一个字符串,分别统计大写字母、小写字母、数字、其他字符的个数,以元组的形式返回结果, 返回的元组的第一个元素依次是字符串 '大写字母'、'小写字母'、'数字' 和 '其他字符',第二个元素是相应的字符个数
时间: 2024-03-29 16:37:01 浏览: 58
可以使用Python内置的字符串方法isupper()、islower()、isdigit()来判断字符是否为大写字母、小写字母、数字。其他字符则可以使用正则表达式判断。
代码如下:
```python
import re
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
elif re.match(r'\W', c):
other_count += 1
return ('大写字母', upper_count), ('小写字母', lower_count), ('数字', digit_count), ('其他字符', other_count)
```
我们可以测试一下:
```python
s = 'Hello, World! This is a test string. 1234567890'
result = count_chars(s)
print(result)
```
输出:
```
(('大写字母', 2), ('小写字母', 25), ('数字', 10), ('其他字符', 12))
```
阅读全文
相关推荐














