用python编写函数接收一个字符串,分别统计大写字母、小写字母、数字、其他字符的个数,并以元组的形式返回结果
时间: 2024-05-07 20:16:19 浏览: 13
```python
def count_chars(s):
upper = 0
lower = 0
digit = 0
other = 0
for c in s:
if c.isupper():
upper += 1
elif c.islower():
lower += 1
elif c.isdigit():
digit += 1
else:
other += 1
return (upper, lower, digit, other)
```
使用示例:
```python
s = "Hello World! 123"
print(count_chars(s)) # 输出 (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
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)
```
使用示例:
```python
s = "Hello World! 123"
result = count_chars(s)
print(result) # 输出:(2, 8, 3, 3)
```
函数接收一个字符串参数 `s`,然后定义四个变量来分别统计大写字母、小写字母、数字、其他字符的个数,最后将这四个变量封装成一个元组并返回。在函数内部,使用了字符串的 `isupper()`、`islower()`、`isdigit()` 方法来判断字符的类型。