ZetCode

Python compare strings

last modified November 19, 2026 Python 3.15

In this article we show how to compare strings in Python.

Strings support all comparison operators. The == and != operators test equality, and <, <=, >, and >= test the order. Both compare the strings character by character, by their Unicode code points. That is fast and well defined, but it is not always what people expect: uppercase letters sort before lowercase ones, and accented letters after all of them. The rest of the article shows how to compare strings the way a reader would.

Equality

Two strings are equal if they have the same characters in the same order.

equality.py
a = 'falcon'
b = 'falcon'
c = 'Falcon'

print(a == b)
print(a == c)
print(a != c)
print(a == 'falcon ')
print('1' == 1)

The comparison is case-sensitive, and a trailing space makes strings different. Comparing a string with a number is not an error; the result is simply False, because Python does not convert the types.

$ python equality.py
True
False
True
False
False

== versus is

The is operator tests whether two names refer to the same object. It must not be used to compare string values.

identity.py
import sys

a = 'falcon'
b = ''.join(['fal', 'con'])

print(a == b)
print(a is b)
print(id(a) == id(b))

c = sys.intern(b)
print(c is a)

The two strings are equal but they are different objects in memory. Python reuses some strings, for example literals in the same code and identifiers; this is called interning. Whether a string is interned is an implementation detail, so is may seem to work in a quick test and fail with strings built at run time. The sys.intern function interns a string explicitly. Comparing with a string literal using is makes Python emit a SyntaxWarning.

$ python identity.py
True
False
False
True

Ordering

The order operators compare strings lexicographically, like words in a dictionary: the first differing character decides.

ordering.py
pairs = [
    ('apple', 'banana'),
    ('apple', 'apricot'),
    ('app', 'apple'),
    ('Zebra', 'apple'),
    ('10', '9'),
    ('é', 'f'),
]

for a, b in pairs:
    print(f'{a!r:8} < {b!r:10} {a < b}')

A prefix is smaller than the longer string. The other results look surprising: Zebra comes before apple, 10 before 9, and é after f.

$ python ordering.py
'apple'  < 'banana'   True
'apple'  < 'apricot'  True
'app'    < 'apple'    True
'Zebra'  < 'apple'    True
'10'     < '9'        True
'é'      < 'f'        False

Code points

The surprising results follow from the code points of the characters. The ord function returns them.

code_points.py
for word in ['Zebra', 'apple', '10', '9', 'é', 'f']:
    print(f'{word!r:8} first code point: {ord(word[0])}')

print(min(['pear', 'Plum', 'apple']), max(['pear', 'Plum', 'apple']))

All uppercase ASCII letters (65 to 90) come before the lowercase ones (97 to 122). The digit 1 is smaller than 9, so 10 sorts before 9. Accented letters lie beyond the ASCII range. The min and max functions use the same order, so the minimum of the list is Plum.

$ python code_points.py
'Zebra'  first code point: 90
'apple'  first code point: 97
'10'     first code point: 49
'9'      first code point: 57
'é'      first code point: 233
'f'      first code point: 102
Plum pear

Ignoring case

To compare strings without regard to case, we convert both to the same case. The casefold method is more thorough than lower.

ignore_case.py
pairs = [
    ('Python', 'PYTHON'),
    ('groß', 'GROSS'),
    ('\ufb01le', 'FILE'),
]

for a, b in pairs:
    print(f'{a} / {b}: lower={a.lower() == b.lower()} '
          f'casefold={a.casefold() == b.casefold()}')

The lower method fails for the German ß, which is written SS in capitals, and for the fi ligature (U+FB01). The casefold method maps both to their plain forms, ss and fi. We use lower for display and casefold for comparison.

$ python ignore_case.py
Python / PYTHON: lower=True casefold=True
groß / GROSS: lower=False casefold=True
file / FILE: lower=False casefold=True

Sorting without case

The key argument of sorted applies a function to each item before comparing.

sort_case.py
words = ['banana', 'Apple', 'cherry', 'apple', 'Banana', 'Cherry']

print(sorted(words))
print(sorted(words, key=str.casefold))
print(sorted(words, key=lambda w: (w.casefold(), w)))

The default order puts all capitalized words first. With key=str.casefold, the words are sorted alphabetically; the sort is stable, so equal keys keep their original order: banana stays before Banana. The tuple key in the last line breaks such ties by the original string, which makes the result independent of the input order.

$ python sort_case.py
['Apple', 'Banana', 'Cherry', 'apple', 'banana', 'cherry']
['Apple', 'apple', 'banana', 'Banana', 'cherry', 'Cherry']
['Apple', 'apple', 'Banana', 'banana', 'Cherry', 'cherry']

Numbers in strings

Version numbers and numbered file names compare digit by digit, not as numbers.

numbers_in_strings.py
versions = ['1.10.0', '1.9.2', '1.2.11', '1.2.9']
files = ['img12.png', 'img2.png', 'img1.png']

print(sorted(versions))
print(sorted(versions, key=lambda v: tuple(map(int, v.split('.')))))
print(max(versions, key=lambda v: tuple(map(int, v.split('.')))))

print(sorted(files))
print(sorted(files, key=lambda f: int(f.removeprefix('img').removesuffix('.png'))))

As strings, 1.10.0 is smaller than 1.9.2. Splitting the version and converting the parts to integers produces tuples, which compare element by element as numbers. The file names get the number between the prefix and the suffix as their key. Python has no built-in natural sort; for real version strings, the packaging.version module handles pre-releases and other details.

$ python numbers_in_strings.py
['1.10.0', '1.2.11', '1.2.9', '1.9.2']
['1.2.9', '1.2.11', '1.9.2', '1.10.0']
1.10.0
['img1.png', 'img12.png', 'img2.png']
['img1.png', 'img2.png', 'img12.png']

Locale-aware order

Languages have their own alphabetical order. In Slovak, č follows c, and the digraph ch is a single letter placed after h. The locale module sorts by the rules of a locale installed on the system.

locale_sort.py
import locale

words = ['chlieb', 'cesta', 'hora', 'čaj', 'ihla', 'Žilina', 'zima']

print(sorted(words))

locale.setlocale(locale.LC_COLLATE, 'sk_SK.UTF-8')
print(sorted(words, key=locale.strxfrm))

print(locale.strcoll('čaj', 'dom') < 0)
print('čaj' < 'dom')

The default order puts čaj and Žilina at the end, because their first letters lie outside ASCII. After setting the collation locale, locale.strxfrm transforms each word into a key that sorts by the Slovak rules: čaj follows cesta, and chlieb follows hora. The locale.strcoll function compares two strings directly and returns a negative number, zero, or a positive number. The program fails with locale.Error if the sk_SK.UTF-8 locale is not installed.

$ python locale_sort.py
['cesta', 'chlieb', 'hora', 'ihla', 'zima', 'čaj', 'Žilina']
['cesta', 'čaj', 'hora', 'chlieb', 'ihla', 'zima', 'Žilina']
True
False

Unicode normalization

The same text can be encoded with different code points. Such strings look identical but are not equal.

normalization.py
import unicodedata

a = 'caf\u00e9'
b = 'cafe\u0301'

print(a, b)
print(a == b)
print(len(a), len(b))

na = unicodedata.normalize('NFC', a)
nb = unicodedata.normalize('NFC', b)
print(na == nb)

print(unicodedata.normalize('NFKC', '\ufb01le \u2460') == 'file 1')

The first string uses the precomposed character é (U+00E9), the second a plain e followed by a combining acute accent (U+0301). macOS file names and some keyboards produce the second form. Normalizing both strings to the NFC form makes them equal. The NFKC form also replaces compatibility characters such as ligatures and circled digits with their plain equivalents.

$ python normalization.py
café café
False
4 5
True
True

Ignoring whitespace

Text from different sources often differs only in spacing. We normalize the whitespace before comparing.

whitespace.py
a = 'An old  silent pond\n'
b = '  an old silent\tpond'


def normalize(s):
    return ' '.join(s.split()).casefold()


print(a == b)
print(a.strip() == b.strip())
print(normalize(a) == normalize(b))

Stripping removes the whitespace at the ends but not the double space and the tab inside. Splitting and joining collapses all whitespace runs into single spaces; together with casefold the two strings compare equal.

$ python whitespace.py
False
False
True

Matching without accents

In the last example we combine the previous techniques to match city names typed without diacritics, a common need in search boxes.

search_names.py
import unicodedata


def fold(text):
    decomposed = unicodedata.normalize('NFKD', text)
    base = ''.join(c for c in decomposed if not unicodedata.combining(c))
    return ' '.join(base.split()).casefold()


cities = ['Košice', 'Žilina', 'Bratislava', 'Banská Bystrica',
          'Nitra', 'Trenčín', 'Prešov']

queries = ['kosice', 'ZILINA', 'banska  bystrica', 'trencin', 'Presov', 'Pest']

index = {fold(city): city for city in cities}

for query in queries:
    city = index.get(fold(query))
    print(f'{query!r:20} -> {city}')

print(sorted(cities, key=fold))

The fold function decomposes each character with the NFKD form, so š becomes s followed by a combining caron. It drops the combining characters, normalizes the whitespace, and folds the case. The index dictionary maps folded names to the original ones, so a lookup costs one dictionary access. Used as a sort key, fold also puts Žilina where an English reader expects it. Letters such as ø or ł have no decomposition and stay unchanged; they need an explicit mapping.

$ python search_names.py
'kosice'             -> Košice
'ZILINA'             -> Žilina
'banska  bystrica'   -> Banská Bystrica
'trencin'            -> Trenčín
'Presov'             -> Prešov
'Pest'               -> None
['Banská Bystrica', 'Bratislava', 'Košice', 'Nitra', 'Prešov', 'Trenčín', 'Žilina']

Source

Value comparisons – Python documentation

str.casefold – Python documentation

locale.strxfrm – Python documentation

In this article we have compared strings in Python. To compare secrets such as tokens, use secrets.compare_digest, shown in Python secrets. See also Python find substring, Python sort list, Python cmp_to_key, and Python string.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.