用Python编写程序,用函数统计大写字母,小写字母,数字,其它字符个数,并以元祖形式返回结果输出
时间: 2024-05-05 21:15:34 浏览: 141
下面是一个示例代码:
```python
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
else:
other_count += 1
return (upper_count, lower_count, digit_count, other_count)
s = 'Hello, World! 123'
counts = count_chars(s)
print('大写字母个数:', counts[0])
print('小写字母个数:', counts[1])
print('数字个数:', counts[2])
print('其它字符个数:', counts[3])
```
运行结果:
```
大写字母个数: 2
小写字母个数: 8
数字个数: 3
其它字符个数: 5
```
相关问题
用Python编写程序,输入一个字符串用函数统计大写字母,小写字母,数字,其它字符个数,并以元祖形式返回结果输出
```
def count_char_types(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 = input("请输入字符串:")
result = count_char_types(s)
print("大写字母个数:", result[0])
print("小写字母个数:", result[1])
print("数字个数:", result[2])
print("其它字符个数:", result[3])
```
python编写函数,接收一个字符串,分别统计大写字母,小写字母,数字,其它字符的个数,并以元祖的形式返回结果
在Python中,你可以编写一个函数来统计字符串中大写字母、小写字母、数字和特殊字符的数量。这里是一个简单的示例:
```python
def count_chars(s):
uppercase = sum(1 for c in s if c.isupper())
lowercase = sum(1 for c in s if c.islower())
digits = sum(1 for c in s if c.isdigit())
others = len(s) - (uppercase + lowercase + digits)
return (uppercase, lowercase, digits, others)
# 使用函数并打印结果
input_string = "Hello World! 123"
result = count_chars(input_string)
print(f"Uppercase: {result[0]}, Lowercase: {result[1]}, Digits: {result[2]}, Others: {result[3]}")
```
这个`count_chars`函数遍历输入的字符串`s`,使用内置的字符串方法如`.isupper()`、`.islower()`和`.isdigit()`检查每个字符是否属于相应的类别。然后计算各类别的字符数量并返回一个包含四个元素的元组。
阅读全文