Concepts / Unicode and character encoding

Unicode and character encoding

Because those characters differ, the comparison is decided immediately.

  • Programming
Interactive lab

Try it: Comparing Strings: Equality and Ordering

How Python compares two strings: == needs the same characters in the same order (capitalisation and spaces count), while <, >, <= and >= walk both strings from the left and let the first differing character decide by its code point — so every uppercase letter sorts before every lowercase one — with a prefix coming before the longer string, and .lower() on both sides making the comparison case-insensitive.

How it works

  1. == and != first compare lengths (different lengths are never equal), then the characters; case and spacing are part of the characters.
  2. <, <=, >, >= compare position 0 of both strings, then 1, 2, …; equal characters move on to the next position.
  3. The FIRST position whose characters differ decides, by their code points (ord): 'A'–'Z' are 65–90 and 'a'–'z' are 97–122, so 'Pineapple' < 'banana' and 'Z' < 'a'. Later characters are never looked at.
  4. If one string runs out first it is a prefix of the other, and the shorter string is smaller ('app' < 'apple'); with no difference at all the strings are equal.
  5. Calling .lower() on both strings before comparing makes capitalisation irrelevant (for equality and for ordering, e.g. sorted(words, key=str.lower)).

Default run (3 steps): Evaluate 'Pineapple' < 'banana'. Ordering compares the strings character by character, by code point (ord), from the left. … So 'Pineapple' < 'banana' is True. sorted([a, b]) would put 'Pineapple' first.

Simplified: Two strings of up to 16 characters (printable ASCII and a few Latin letters, all below U+0100, so code point and alphabet order are the same thing here). Results, .lower() and sorted() order match CPython 3.12 on 900+ random pairs.

Educational simulation

Loading the simulation…

A Comparison Begins at the First Character

When Python compares two strings, it does not treat each string as an indivisible whole. It examines their characters from left to right. The first pair of different characters determines the result. If the characters at one position match, Python continues to the next position.

What do you think happens?

What is the result of comparing 'apple' and 'banana' with the less-than operator?

  • True

  • False

  • The comparison cannot be decided

Reveal answer
Answer:

True

Python compares the first characters, 'a' and 'b'. Because 'a' has a lower Unicode value than 'b', the comparison is decided at position 0. The remaining characters do not need to be examined.

aposition 0bposition 0True'apple' < 'banana'pposition 1aposition 1compare position 0'a' is lower than 'b'
How does Python compare two strings one character at a time, and what happens when it finds the first differing character?

Operators for Equality and Order

The equality operator, ==, checks whether two strings are exactly the same. The comparison returns True only when both strings contain the same characters in the same order. The less-than operator, <, returns True when the first string comes before the second alphabetically. The greater-than operator, >, returns True when the first string comes after the second alphabetically.

OperatorQuestion it asksTrue when
==Are the strings exactly the same?Both strings have the same characters in the same order
<Does the first string come before the second?The first string comes before the second alphabetically
>Does the first string come after the second?The first string comes after the second alphabetically

The three string comparison operators described in the source material.

Worked example

Choosing the correct operator

Compare a string with the reference string 'banana'. Decide which operator expresses each question.

  1. 1
    Check identity

    Use == when the question is whether the string is exactly 'banana', with the same characters in the same order.

  2. 2
    Check earlier order

    Use < when the question is whether the string comes before 'banana' alphabetically.

  3. 3
    Check later order

    Use > when the question is whether the string comes after 'banana' alphabetically.

Result

The operator must match the question: == tests exact equality, < tests earlier alphabetical order, and > tests later alphabetical order.

Tracing Unicode Values from Left to Right

Python uses Unicode values when comparing characters. For 'apple' and 'banana', it compares 'a' with 'b' at position 0. Because those characters differ, the comparison is decided immediately. If two strings begin with the same character, Python moves to the next position. For example, 'apple' and 'apricot' share their first character, so the comparison continues to the next character rather than being decided at the beginning.

alower Unicode valueasame Unicode value atposition 0next positioncontinue when charactersmatchpnext position if neededpsame Unicode value atposition 1compare position 0compare position 1characters matchcharacters match
How does each character correspond to a Unicode value that Python can use during comparison?
Key point

Lexicographical comparison is sequential: compare position 0 first, then position 1 only if necessary, and continue until a difference determines the result.

Case Changes the Result

String comparison is case-sensitive. An uppercase letter and its lowercase version are treated as different characters because they have different Unicode values. Therefore, 'Apple' and 'apple' are not equal. The source also states that 'Apple' < 'apple' is True because uppercase letters have lower Unicode values than lowercase letters.

Appleuppercase AFalse'Apple' == 'apple'applelowercase aTrue'Apple' < 'apple'different first charactersdifferent first characterslower Unicode value at position 0higher Unicode value at position 0
Why can uppercase and lowercase versions of the same letter produce different comparison results?

Debugging an Unexpected Comparison

When a comparison produces an unexpected result, trace both strings from left to right. Check whether the characters at position 0 match. If they do, inspect position 1, then the next position. The first mismatch is the most important evidence because it determines the comparison. Also check capitalization at that position.

Two stringsCompare a positionleft to rightCharacters matchNext positioncontinue the traceComparison result==, <, or >First differenceUnicode values decidebegininspect charactersyesnodeciderepeat
Which character position causes two strings to compare as unequal or appear in an unexpected order?
  • Common mistake

    Treating equality as a loose match

    What it looks like

    Assuming that 'banana' and 'Banana' are equal

    Why it fails

    The strings do not contain the same characters: their first characters differ in case.

    Do this instead

    Remember that == requires the same characters in the same order, and string comparison is case-sensitive.

  • Common mistake

    Reading every character before deciding the order

    What it looks like

    Comparing all of 'apple' and 'banana' even after seeing 'a' and 'b'

    Why it fails

    The first characters already differ, so their Unicode values decide the result.

    Do this instead

    Stop at the first differing character when tracing a comparison.

  • Common mistake

    Using the wrong relational direction

    What it looks like

    Using > when checking whether a word comes before 'banana'

    Why it fails

    The < operator checks whether the first string comes before the second; > checks whether it comes after.

    Do this instead

    Translate the question into before, after, or exactly equal before choosing the operator.

Best practice

For a failed comparison, write the two strings in aligned positions and identify the first mismatch. Record whether the mismatch is caused by a different letter or by uppercase versus lowercase. This gives you a concrete reason for the result instead of treating the comparison as unpredictable.

Applying the Three-Way Check

A comparison can be organized into three cases: the string comes before the reference string, comes after it, or equals it. The source describes a structure using <, >, and an else branch for equality. The equality case is reached after the string is neither less than nor greater than the reference string.

MEDIUM

For each pair, identify the first position that decides the result and choose the correct conclusion: equal, first string comes before, or first string comes after. Pair 1: 'apple' and 'banana'. Pair 2: 'apple' and 'apricot'. Pair 3: 'Apple' and 'apple'.

Hints
  • Begin at position 0 for every pair.
  • If the characters match, move to the next position.
  • Check case carefully in Pair 3.
Worked example

Tracing a comparison

Determine the result of comparing 'apple' and 'apricot' in alphabetical order.

  1. 1
    Position 0

    Both strings begin with 'a', so the comparison is not decided yet.

  2. 2
    Position 1

    Both strings have 'p' at position 1, so continue.

  3. 3
    Position 2

    The strings differ: 'p' in 'apple' is compared with 'r' in 'apricot'. This is the first difference, so it determines the order.

Result

'apple' comes before 'apricot' because the first differing character in 'apple' has a lower Unicode value than the corresponding character in 'apricot'.

What to Remember

  1. 1
    Use == to test whether two strings have exactly the same characters in the same order.
  2. 2
    Use < and > to determine whether one string comes before or after another alphabetically.
  3. 3
    Python compares strings lexicographically from left to right and stops when the first differing character decides the result.
  4. 4
    Unicode values determine how corresponding characters compare.
  5. 5
    String comparison is case-sensitive, so uppercase and lowercase letters can produce different equality and ordering results.

At a glance

  • String equality requires identical characters in identical order.
  • Relational operators compare strings alphabetically using lexicographical order.
  • Python checks characters from left to right and uses the first difference to decide the result.
  • Unicode values and case affect the comparison, so uppercase and lowercase versions of a letter are distinct.
  • To debug a comparison, trace both strings position by position and inspect the first mismatch.

More concepts starting with U