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

การเปรียบเทียบสตริงแบบ Case-insensitive ใน Python

วิธีมาตรฐาน: แปลงทั้งสองสตริงให้เป็นพิมพ์เล็ก (หรือพิมพ์ใหญ่) ก่อนเปรียบเทียบ

ตัวอย่าง

string1 = 'Star Wars'
string2 = 'star wars'

if string1.lower() == string2.lower():
    print("The strings are case insensitive")
else:
    print("The strings are not case insensitive")

ผลลัพธ์

The strings are case insensitive

วิธีอื่นๆ

1. str.casefold() (แนะนำสำหรับ Unicode)

>> 'Straße'.lower()
'straße'
>>> 'Straße'.casefold()
'strasse'  # จัดการ ß → ss ได้ถูกต้อง

>>> 'STRAßE'.casefold() == 'Straße'.casefold()
True

2. re.IGNORECASE (Regex)

>> import re
>>> bool(re.search('star wars', 'Star Wars', re.IGNORECASE))
True

3. str.upper() (เหมือน lower)

>> 'Star Wars'.upper() == 'STAR WARS'
True

สรุป: ควรใช้ตัวไหน?

  • ASCII เท่านั้น: .lower() หรือ .upper() (เร็วกว่า)
  • Unicode/International: .casefold() (ถูกต้องกว่า ตาม Unicode Standard)
  • Pattern Matching: re.IGNORECASE