Compare Strings in Python

Learn how to compare strings in Python using equality, ordering operators, and case-insensitive comparison with practical examples and Unicode-aware techniques.

5 min read

Comparing strings in Python is something you do whenever you validate a password, check whether a username already exists, sort a list of names alphabetically, or determine whether two pieces of text match exactly. Python supports the full set of comparison operators on strings: double-equals for equality, not-equals for inequality, and the less-than and greater-than family for ordering. These operators work directly on string objects without requiring any special method calls, and they behave consistently with how comparisons work across all Python types.

String comparison in Python is case-sensitive by default. The strings "Python" and "python" are not equal because the first character differs in case, even though a human reader would recognize them as the same word. For case-insensitive matching, you convert both strings to a common case before comparing, and the casefold() method covered in the article on changing string case is the correct tool for this job. For exact substring matching and position-based searches, the article on search and replace covers find() and the in operator.

This article explains how Python's comparison operators work on strings, what lexicographic ordering means and why it sometimes produces surprising sort results, and how to perform case-insensitive comparisons correctly. It also briefly covers how string comparison interacts with Python's identity operator is, a topic explored in detail in the earlier article on string immutability.

Equality and ordering with standard operators

The double-equals operator checks whether two strings contain exactly the same sequence of Unicode code points. This is a character-by-character comparison that requires the strings to be identical in every position. The not-equals operator returns True when the strings differ in any way. Both operators are case-sensitive, so changing even one character from uppercase to lowercase makes the strings unequal.

The ordering operators, which are less-than, greater-than, less-than-or-equal, and greater-than-or-equal, compare strings lexicographically. Lexicographic comparison works like dictionary ordering: Python compares the first character of each string using its Unicode code point value. If they differ, the string with the lower code point is considered smaller. If they are equal, Python moves to the second character and repeats the process. If one string runs out of characters while all compared characters have been equal, the shorter string is considered smaller.

pythonpython
print("apple" < "banana")    # True (a comes before b)
print("apple" < "Apple")     # False (lowercase a has higher code than uppercase A)
print("apple" == "Apple")    # False (case matters)

The fact that lexicographic ordering uses Unicode code points rather than natural language rules has practical consequences. All uppercase letters have lower code point values than all lowercase letters, which means "Zebra" sorts before "apple" in a standard Python sort. If you need natural alphabetical ordering that ignores case, convert all strings to a consistent case before sorting.

Case-insensitive matching with casefold()

For comparing strings without regard to case, the standard pattern is to call casefold() on both strings and then compare the results with the double-equals operator. The casefold() method is preferred over lower() because it handles special cases in languages beyond English where lowercasing alone is insufficient to remove all case distinctions.

This pattern appears constantly in user authentication, search functionality, data deduplication, and any situation where the meaning of the text matters more than its exact capitalization. It is simple, reliable, and works correctly across the full range of Unicode text.

A common optimization is to store a casefolded version of text alongside the original when you know you will perform many case-insensitive searches. Comparing pre-casefolded strings avoids calling casefold() repeatedly on the same data, which matters when processing large datasets or handling high-traffic web requests. The tradeoff is storage space versus computation time, and for most beginner and intermediate applications, calling casefold() at comparison time is perfectly adequate.

Rune AI

Rune AI

Key Insights

  • Use == and != for exact string equality checks; comparisons are case-sensitive by default.
  • The <, >, <=, and >= operators perform lexicographic comparison based on Unicode code points.
  • For case-insensitive comparison, call casefold() on both strings before using ==.
  • Lexicographic ordering means uppercase letters sort before lowercase, which differs from dictionary ordering.
  • All comparison operators work directly on strings; no special method calls are required.
RunePowered by Rune AI

Frequently Asked Questions

How do I check if two strings are equal in Python?

Use the double-equals operator. Writing string1 == string2 returns True if the two strings contain exactly the same characters in the same order, and False otherwise. The != operator checks for inequality. String comparison in Python is case-sensitive by default, so 'Hello' == 'hello' returns False. For case-insensitive equality, call casefold() on both strings first.

Can I use greater-than and less-than operators with strings?

Yes. Python compares strings lexicographically, which means it compares them character by character using the Unicode code point value of each character. This is similar to dictionary ordering: 'apple' < 'banana' is True because a comes before b. All capital letters come before all lowercase letters in Unicode, so 'Z' < 'a' is True, which can be surprising if you expect natural alphabetical ordering.

How do I do a case-insensitive string comparison?

Call the casefold() method on both strings before comparing. The expression string1.casefold() == string2.casefold() returns True if the strings are equal regardless of case. Use casefold() rather than lower() because casefold() handles special cases across languages, such as the German letter ß matching ss. Avoid using upper() for this purpose; casefold() is specifically designed for caseless matching.

Conclusion

Comparing strings in Python is straightforward with the standard comparison operators, and casefold() adds reliable case-insensitive matching. Understanding that comparisons are case-sensitive and lexicographic by default helps you avoid surprises, and knowing that Unicode code point ordering differs from natural language ordering prepares you for the rare cases where sorted() produces unexpected results.