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

Find List Elements Starting with Specific Letter ใน Python

ได้ลิสต์สตริง และตัวอักษรเป้าหมาย หาสมาชิกทั้งหมดที่ขึ้นต้นด้วยตัวอักษรนั้น (ไม่สนใจพิมพ์ใหญ่/เล็ก)

วิธี 1: ใช้ Index [0] กับ lower()

listA = ['Mon', 'Tue', 'Wed', 'Thu']
target = 'T'
res = [s for s in listA if s[0].lower() == target.lower()]
print(res)  # ['Tue', 'Thu']

วิธี 2: ใช้ startswith() (Pythonic กว่า)

listA = ['Mon', 'Tue', 'Wed', 'Thu']
target = 'T'
res = [s for s in listA if s.lower().startswith(target.lower())]
print(res)  # ['Tue', 'Thu']

สรุป

startswith() อ่านง่ายกว่า จัดการสตริงว่างได้ (ไม่ Error) และรองรับ Prefix หลายตัวอักษร