Library contents

Python str.casefold

Compare two ASCII booking codes while ignoring uppercase and lowercase differences.

A simple example

str.casefold

  1. Start with "a" and "A"
  2. Do this Compare ignoring case
  3. Result Equal
After case is ignored the two ASCII letters represent the same text.
lesson.py
value = "a"
other = "A"
print("yes" if value.casefold() == other.casefold() else "no")
Output
yes

Syntax

Python syntax
"AB".casefold() == "ab".casefold()
Run these examples in Python

Save one example at a time as lesson.py. Use Python 3.9 or later.

python3 lesson.py

Match a booking code regardless of letter case

People enter short codes with different keyboard settings and capitalization. Match the input under the intended case rule so a valid code can be recognized without changing the stored identifier.

From the programprint("yes" if "AB".casefold() == "ab".casefold() else "no")
Resultyes
lesson.py
print("yes" if "AB".casefold() == "ab".casefold() else "no")
Output
yes

A code printed as AB and a code entered as ab identify the same booking under this policy.

Advertisements

Accept an airport code typed in lowercase

A traveler types an airport code on a phone that defaults to lowercase. The lookup should recognize the airport even when the typed letters differ in case from the stored abbreviation.

From the programvalue = "maa"
Resultyes
lesson.py
value = "maa"
other = "MAA"
print("yes" if value.casefold() == other.casefold() else "no")
Output
yes

Only the capitalization differs.

Keep different seat numbers distinct

A reader compares two identifiers that may look similar on their labels. Use the full values under the intended case rules so a difference in one letter or digit is not lost.

From the programvalue = "b12"
Resultno
lesson.py
value = "b12"
other = "B21"
print("yes" if value.casefold() == other.casefold() else "no")
Output
no

Ignoring case does not change digit order.

What to watch for

Use this policy only for fields whose specification permits it. Passwords and many identifiers are case-sensitive.

Documentation for str.casefold