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