在 Python 程式中統計字串中出現的英文小寫字元數量


如果需要統計字串中出現的小寫字元數量,可以使用 ‘islower’ 方法和一個簡單的 ‘for’ 迴圈。

以下是演示示例 −

示例

 現場演示

my_string = "Hi there how are you"
print("The string is ")
print(my_string)
my_counter=0

for i in my_string:
   if(i.islower()):
      my_counter=my_counter+1
print("The number of lowercase characters in the string are :")
print(my_counter)

輸出

The string is
Hi there how are you
The number of lowercase characters in the string are :
15

解釋

  • 一個字串被定義並顯示在控制檯上。

  • 一個計數器值被初始化為 0。

  • 該字串被迭代,並使用 ‘islower’ 方法檢查它是否包含小寫字母。

  • 如果是,則計數器增 1,直到字串結束。

  • 這將作為輸出顯示在控制檯上。

更新於: 2021-04-17

2 千次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.