Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python – กรองสตริงที่เป็นตัวพิมพ์ใหญ่ทั้งหมดหรือตัวพิมพ์เล็กทั้งหมด (Same Case)

ภาพรวม

กรองเฉพาะสตริงที่เป็น uppercase ทั้งหมด หรือ lowercase ทั้งหมด โดยใช้ isupper() และ islower() ร่วมกับ list comprehension

ตัวอย่างโค้ด

my_list = ["Python", "good", "FOr", "few", "CODERS"]
print("The list is:", my_list)

my_result = [s for s in my_list if s.islower() or s.isupper()]
print("The strings with same case are:", my_result)

ผลลัพธ์

The list is: ['Python', 'good', 'FOr', 'few', 'CODERS']
The strings with same case are: ['good', 'few', 'CODERS']

คำอธิบาย

  • "Python" – มีทั้ง upper (P) และ lower (ython) -> ไม่ผ่าน
  • "good" – ทั้งหมด lower -> ผ่าน
  • "FOr" – มี F, O upper, r lower -> ไม่ผ่าน
  • "few" – ทั้งหมด lower -> ผ่าน
  • "CODERS" – ทั้งหมด upper -> ผ่าน

ขยายความสามารถ

# แยกเป็น 2 กลุ่ม
lower_only = [s for s in my_list if s.islower()]
upper_only = [s for s in my_list if s.isupper()]
mixed_case = [s for s in my_list if not (s.islower() or s.isupper())]

# ตรวจสอบ title case (ตัวแรกใหญ่ ที่เหลือเล็ก)
title_case = [s for s in my_list if s.istitle()]