编写一个程序输入一个字符串分别计算,其中小写字符大写字符数字其他字符的个数。
时间: 2024-04-30 22:25:19 浏览: 20
以下是 Python 代码实现:
```python
string = input("请输入一个字符串:")
lower_count = upper_count = digit_count = 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)
```
程序会先让用户输入一个字符串,然后使用 for 循环遍历字符串中的每个字符。对于每个字符,使用 islower()、isupper()、isdigit() 函数判断它是小写字符、大写字符、数字还是其他字符,并分别计数。最后输出每种类型字符的个数。
相关问题
编写一个程序,输入一个字符串,分别计算其中小写字符、大写字符、数字、其他字符的个数
可以使用循环遍历字符串中的每个字符,然后根据字符的 ASCII 码值来判断其属于哪个类别。
以下是一个简单的 Python 代码示例:
```python
s = input("请输入一个字符串:")
lower_count = 0 # 小写字符个数
upper_count = 0 # 大写字符个数
digit_count = 0 # 数字个数
other_count = 0 # 其他字符个数
for c in s:
if c.islower():
lower_count += 1
elif c.isupper():
upper_count += 1
elif c.isdigit():
digit_count += 1
else:
other_count += 1
print("小写字符个数:", lower_count)
print("大写字符个数:", upper_count)
print("数字个数:", digit_count)
print("其他字符个数:", other_count)
```
此程序通过内置函数 `islower()`、`isupper()`、`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。最后打印出各个计数器的值。