编写程序,输入任意一个字符串,分别统计大写字母、小写字母、数字及其他字符的个数,输出各个统计结果。
时间: 2024-12-02 14:13:51 浏览: 60
可以使用Python的内置函数来完成这个任务,这里是一个简单的例子:
```python
def count_chars(input_string):
uppercase_count = sum(1 for c in input_string if c.isupper())
lowercase_count = sum(1 for c in input_string if c.islower())
digit_count = sum(1 for c in input_string if c.isdigit())
other_count = len(input_string) - (uppercase_count + lowercase_count + digit_count)
print(f"大写字母:{uppercase_count}")
print(f"小写字母:{lowercase_count}")
print(f"数字:{digit_count}")
print(f"其他字符:{other_count}")
input_string = input("请输入任意字符串:")
count_chars(input_string)
```
这个程序通过遍历输入的字符串,并使用`isupper()`、`islower()`和`isdigit()`函数判断每个字符是否为大写字母、小写字母或数字,然后计算相应的计数。剩下的就是不属于这三类的字符,即其他字符。
相关问题
编写函数接收一个字符串分别统计大写字母小写字母数字其他字符的个数
以下是Python语言的代码实现:
```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
```
该函数接收一个字符串作为参数,使用循环遍历字符串中的每个字符,根据字符的类型增加相应的计数器。最后返回各种字符的数量。可以使用多重赋值来获取返回值中的各项数量:
```python
s = "Hello, World! 123"
upper_count, lower_count, digit_count, other_count = count_chars(s)
print("Upper case count:", upper_count)
print("Lower case count:", lower_count)
print("Digit count:", digit_count)
print("Other count:", other_count)
```
输出如下:
```
Upper case count: 2
Lower case count: 8
Digit count: 3
Other count: 3
```
编写函数接收一个字符串分别统计大写字母小写字母数字其他字符的个数,并以元组的形式返回结果
以下是Python代码实现:
```python
def count_chars(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`,然后遍历字符串中的每个字符,使用 `isupper()`、`islower()` 和 `isdigit()` 方法判断字符是否是大写字母、小写字母和数字。如果不是这三个类型的字符,则计入“其他字符”数目中。最后将四个计数器作为元组返回。
阅读全文
相关推荐















