编写生成器函数,接收一个字符串,分别统计大写字母、小写字母、数字、其他字符的个数,并以元组的形式返回结果
时间: 2023-12-12 14:56:23 浏览: 17
好的,这是生成器函数的代码:
```python
def count_chars(string):
upper_count = 0
lower_count = 0
digit_count = 0
other_count = 0
for char in string:
if char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1
elif char.isdigit():
digit_count += 1
else:
other_count += 1
yield (upper_count, lower_count, digit_count, other_count)
```
你可以使用它来统计一个字符串中各种字符的数量,例如:
```python
string = "Hello World! 123"
result = next(count_chars(string))
print(result) # 输出 (2, 8, 3, 3)
```
这里的结果表示该字符串中有 2 个大写字母、8 个小写字母、3 个数字和 3 个其他字符。
相关问题
编写函数接收一个字符串分别统计大写字母小写字母数字其他字符的个数,并以元组的形式返回结果
以下是Python代码实现:
```python
def count_chars(s):
upper_count = 0
lower_count = 0
digit_count = 0
other_count = 0
for char in s:
if char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1
elif char.isdigit():
digit_count += 1
else:
other_count += 1
return (upper_count, lower_count, digit_count, other_count)
```
这个函数接收一个字符串 `s`,然后遍历字符串中的每个字符,使用 `isupper()`、`islower()` 和 `isdigit()` 方法判断字符是否是大写字母、小写字母和数字。如果不是这三个类型的字符,则计入“其他字符”数目中。最后将四个计数器作为元组返回。
1. 编写生成器函数,接收一个字符串,分别统计大写字母、小写字母、数字、其他字符的个数,并以元组的形式返回结果
好的,我可以帮您编写这个生成器函数。以下是代码实现:
```python
def count_chars(string):
upper_count = 0
lower_count = 0
digit_count = 0
other_count = 0
for char in string:
if char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1
elif char.isdigit():
digit_count += 1
else:
other_count += 1
return (upper_count, lower_count, digit_count, other_count)
```
这个函数接收一个字符串作为参数,然后遍历字符串中的每个字符,判断它是大写字母、小写字母、数字还是其他字符,并分别记录它们的数量。最后,将这些数量打包成元组并返回。
您可以在代码中调用这个函数,例如:
```python
result = count_chars("Hello, World! 123")
print(result)
```
输出结果为:
```
(2, 8, 3, 3)
```
其中,元组的四个元素分别代表大写字母数量、小写字母数量、数字数量和其他字符数量。