统计输入字符串中大写字母、小写字母、数字字符及其他字符的个数。Python
时间: 2023-06-23 12:09:29 浏览: 184
可以使用 Python 中的 isupper()、islower()、isdigit() 等函数判断字符的类型,然后统计各个类型的字符数量即可。下面是一个示例代码:
```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("Uppercase count:", counts[0])
print("Lowercase count:", counts[1])
print("Digit count:", counts[2])
print("Other count:", counts[3])
```
输出结果为:
```
Uppercase count: 2
Lowercase count: 8
Digit count: 3
Other count: 4
```
阅读全文