用python输入一个字符串,分别计算其中小写字母、大写字母、数字、其它字符的个数。
时间: 2024-04-29 22:23:33 浏览: 15
代码如下:
```python
s = input("请输入一个字符串:")
lowercase = 0 # 小写字母个数
uppercase = 0 # 大写字母个数
digit = 0 # 数字个数
other = 0 # 其它字符个数
for c in s:
if c.islower():
lowercase += 1
elif c.isupper():
uppercase += 1
elif c.isdigit():
digit += 1
else:
other += 1
print("小写字母个数:", lowercase)
print("大写字母个数:", uppercase)
print("数字个数:", digit)
print("其它字符个数:", other)
```
运行示例:
```
请输入一个字符串:Hello, World! 123
小写字母个数: 3
大写字母个数: 2
数字个数: 3
其它字符个数: 7
```
相关问题
输入一个字符串,分别计算其中小写字母、大写字母、数字、其它字符的个数。
可以使用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()` 方法来判断字符的类型,并分别累加计数。最后将各个计数值作为元组返回。