输入一个字符串,分别计算其中小写字母、大写字母、数字、其它字符的个数。
时间: 2023-12-13 09:05:49 浏览: 31
可以使用Python中的字符串方法islower()、isupper()、isdigit()来判断一个字符是否为小写字母、大写字母、数字。
代码如下:
```python
string = input("请输入一个字符串:")
lower_count = 0
upper_count = 0
digit_count = 0
other_count = 0
for char in string:
if char.islower():
lower_count += 1
elif char.isupper():
upper_count += 1
elif char.isdigit():
digit_count += 1
else:
other_count += 1
print("小写字母个数:", lower_count)
print("大写字母个数:", upper_count)
print("数字个数:", digit_count)
print("其它字符个数:", other_count)
```
运行示例:
```
请输入一个字符串:Hello, World! 123
小写字母个数: 4
大写字母个数: 2
数字个数: 3
其它字符个数: 6
```
相关问题
输入一个字符串,计算其中小写字母、大写字母、数字字符、其他字符的个数
好的,以下是 Python 代码实现:
```python
def count_chars(string):
upper = 0 # 大写字母计数
lower = 0 # 小写字母计数
digit = 0 # 数字字符计数
other = 0 # 其他字符计数
for char in string:
if char.isupper():
upper += 1
elif char.islower():
lower += 1
elif char.isdigit():
digit += 1
else:
other += 1
return upper, lower, digit, other
# 测试
string = "Hello, World! 123"
print(count_chars(string)) # 输出 (2, 8, 3, 4)
```
以上代码中,我们使用了 Python 的 `isupper()`、`islower()` 和 `isdigit()` 方法来判断字符的类型,并分别累加计数。最后将各个计数值作为元组返回。
输入一个字符串,分别计算其中小写字符大写字符数字,其他字符的个数
这是一个Python的例子,可以统计一个字符串中小写字母、大写字母、数字和其他字符的数量:
```python
s = input("请输入一个字符串:")
lowers = uppers = digits = others = 0
for c in s:
if c.islower():
lowers += 1
elif c.isupper():
uppers += 1
elif c.isdigit():
digits += 1
else:
others += 1
print("小写字母个数:", lowers)
print("大写字母个数:", uppers)
print("数字个数:", digits)
print("其他字符个数:", others)
```
这个程序首先读入一个字符串,然后遍历字符串中的每个字符,对于每个字符,如果它是小写字母,就将小写字母计数器加1;如果它是大写字母,就将大写字母计数器加1;如果它是数字,就将数字计数器加1;否则就将其他字符计数器加1。最后打印出各个计数器的值。