Python 程序计算字符串中小写字母的数量

pythonserver side programmingprogramming更新于 2023/12/23 9:01:00

当需要计算字符串中小写字母的数量时,可以迭代字符串。可以检查它是否包含小写字母,并且可以增加计数器。

以下是同样的演示 −

示例

my_string = "Hi there how are you"
print("字符串为:")
print(my_string)
my_counter=0
for i in my_string:
   if(i.islower()):
      my_counter=my_counter+1
print("小写字母的数量为:")
print(my_counter)

输出

字符串为:
Hi there how are you
小写字母的数量为:
15

解释

  • 定义一个字符串,并显示在控制台上。

  • 计数器初始化为 0。

  • 字符串被迭代。

  • 检查它是否为小写。

  • 如果是小写,计数器递增。

  • 这是显示在控制台上的输出。


相关文章