เมื่อต้องการนับตัวอักษรพิมพ์เล็กในสตริง ใช้เมธอด islower() ร่วมกับลูป for
ตัวอย่างโค้ด
my_string = "Hi there how are you"
print("The string is:", my_string)
count = 0
for ch in my_string:
if ch.islower():
count += 1
print("Number of lowercase characters:", count)ผลลัพธ์
The string is: Hi there how are you Number of lowercase characters: 15
คำอธิบาย
กำหนดตัวแปรนับ
count = 0วนลูปผ่านทุกตัวอักษรในสตริง
ch.islower()คืน True ถ้า ch เป็นตัวพิมพ์เล็ก (a-z)เพิ่มตัวนับเมื่อเจอตัวพิมพ์เล็ก
เว้นวรรคและเครื่องหมายวรรคตอนจะคืน False