python编写函数,接收一个字符串,分别统计大写字母,小写字母,数字,其他字符的个数,并以元组的形式返回结果
时间: 2023-08-13 13:02:26 浏览: 191
好的,下面是代码实现:
```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
s = "Hello, world! 123"
print(count_chars(s)) # 输出结果为 (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()` 方法判断字符是否是大写字母、小写字母和数字。如果不是这三个类型的字符,则计入“其他字符”数目中。最后将四个计数器作为元组返回。
Python编写函数 接收一个字符串 统计大写字母 小写字母 数字和其他字符的个数 并以元组的形式返回结果
在Python中,你可以编写一个函数来完成这个任务。下面是一个简单的函数示例,它接受一个字符串作为输入,然后分别统计其中的大写字母、小写字母、数字和非字母数字字符的数量,并以元组形式返回这些计数值:
```python
def count_chars(input_string):
uppercase = sum(1 for char in input_string if char.isupper())
lowercase = sum(1 for char in input_string if char.islower())
digits = sum(1 for char in input_string if char.isdigit())
others = len(input_string) - (uppercase + lowercase + digits)
return (uppercase, lowercase, digits, others)
# 使用示例
example_str = "HelloWorld123!"
result = count_chars(example_str)
print(result) # 输出: (2, 8, 3, 1)
```
这个函数通过`isupper()`、`islower()`和`isdigit()`方法检查每个字符的类型,然后使用列表推导式计算满足条件的字符数量。最后返回的是一个包含四个元素的元组,代表大写字母、小写字母、数字和其他字符的数量。
阅读全文
相关推荐












