python统计大小写字母个数

2023-07-30 大小 个数 写字母

下面给出一个Python程序,可以统计给定字符串中的大写字母、小写字母和数字的数量,可以自动忽略空格和标点符号。以"pidancode.com"字符串为例,代码演示如下:

string = "pidancode.com"
count_upper = 0
count_lower = 0
count_digit = 0

for char in string:
    if char.isupper():
        count_upper += 1
    elif char.islower():
        count_lower += 1
    elif char.isdigit():
        count_digit += 1

print("大写字母数量:", count_upper)
print("小写字母数量:", count_lower)
print("数字数量:", count_digit)

输出结果为:

大写字母数量: 0
小写字母数量: 12
数字数量: 0

此时的结果符合预期,因为字符串中均为小写字母,没有大写字母和数字。如果换成"皮蛋编程"字符串,则输出结果为:

大写字母数量: 0
小写字母数量: 5
数字数量: 0

同样的,此时的结果也符合预期。通过这段程序,我们可以方便地统计字符串中不同类型字符的数量。

相关文章