Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to compare strings in Python

Introduction

Strings are one of the most common data types in programming languages, including Python. They are used to represent text and can contain letters, numbers, and special characters. When working with strings, it's often necessary to compare them for various reasons, such as checking for equality or sorting them in alphabetical order. In this blog post, we will explore different ways to compare strings in Python, including the use of comparison operators, built-in functions, and special methods. We will also discuss some practical examples and tips to help you better understand the concepts.

String Comparison Basics

In Python, strings can be compared using comparison operators like ==, !=, <, >, <=, and >=. These operators compare the strings based on their lexicographic (dictionary) order, which is the order in which they would appear in a dictionary. Here's a brief explanation of each operator:

  • ==: Returns True if the two strings are equal, False otherwise.
  • !=: Returns True if the two strings are not equal, False otherwise.
  • <: Returns True if the first string comes before the second string in lexicographic order, False otherwise.
  • >: Returns True if the first string comes after the second string in lexicographic order, False otherwise.
  • <=: Returns True if the first string comes before or is equal to the second string in lexicographic order, False otherwise.
  • >=: Returns True if the first string comes after or is equal to the second string in lexicographic order, False otherwise.

Here are some examples of string comparisons using these operators:

print("apple" == "apple")  # True
print("apple" != "banana")  # True
print("apple" < "banana")   # True
print("apple" > "banana")   # False
print("apple" <= "banana")  # True
print("apple" >= "banana")  # False

Keep in mind that these operators are case-sensitive, so "Apple" and "apple" would be considered different strings. If you want to perform a case-insensitive comparison, you can convert both strings to lowercase (or uppercase) using the lower() (or upper()) method before comparing them.

print("Apple".lower() == "apple".lower())  # True

Comparing Strings with Built-in Functions

Python provides some built-in functions that can be used to compare strings as well. These functions offer more control over the comparison process and can be useful in different scenarios.

The ord() and chr() functions

The ord() function returns the Unicode code point (integer representation) of a given character, while the chr() function returns the character corresponding to a given Unicode code point. These functions can be useful when you want to compare individual characters in a string based on their Unicode values.

print(ord("A"))    # 65
print(ord("a"))    # 97
print(chr(65))     # A
print(chr(97))     # a

You can use the ord() function to compare characters based on their Unicode values like this:

print(ord("A") < ord("a"))  # True

The sorted() function

The sorted() function can be used to sort a collection of strings in lexicographic order. By default, the function returns a new list containing the sorted strings, but you can also pass a custom sorting function to the key parameter if you need more control over the sorting process.

Here's an example of how to use the sorted() function to sort a list of strings:

fruits = ["apple", "banana", "cherry", "kiwi", "mango", "watermelon"]
sorted_fruits = sorted(fruits)
print(sorted_fruits)
# Output: ['apple', 'banana', 'cherry', 'kiwi', 'mango', 'watermelon']

If you want to sort the strings in descending order, you can pass the reverse=True parameter:

sorted_fruits_desc = sorted(fruits, reverse=True)
print(sorted_fruits_desc)
# Output: ['watermelon', 'mango', 'kiwi', 'cherry', 'banana', 'apple']

You can also perform a case-insensitive sort by passing the str.lower function as the key parameter:

fruits_mixed_case = ["Apple", "banana", "Cherry", "kiwi", "Mango", "Watermelon"]
sorted_fruits_case_insensitive = sorted(fruits_mixed_case, key=str.lower)
print(sorted_fruits_case_insensitive)
# Output: ['Apple', 'banana', 'Cherry', 'kiwi', 'Mango', 'Watermelon']

Comparing Strings Using Special Methods

In addition to the comparison operators and built-in functions, Python strings have some special methods that can be used to compare them in various ways. These methods can be especially useful when working with custom classes or more complex data structures.

The __eq__() and __ne__() methods

The __eq__() and __ne__() methods are used to implement the == and != operators, respectively. You can override these methods in your custom classes to define how instances of the class should be compared for equality or inequality. Here's a simple example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __eq__(self, other):
        if isinstance(other, Person):
            return self.name.lower() == other.name.lower() and self.age == other.age
        return False

    def __ne__(self, other):
        return not self.__eq__(other)

person1 = Person("Alice", 30)
person2 = Person("alice", 30)
person3 = Person("Bob", 25)

print(person1 == person2)  # True
print(person1 != person3)  # True

In this example, the __eq__() method compares two Person instances for equality by comparing their names (case-insensitive) and ages. The __ne__() method simply returns the opposite of the __eq__() method.

The __lt__() and __gt__() methods

The __lt__() and __gt__() methods are used to implement the < and > operators, respectively. You can override these methods in your custom classes to define how instances of the class should be compared for less than or greater than. Here's an example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __lt__(self, other):
        if isinstance(other, Person):
            return self.age < other.age
        return NotImplemented

    def __gt__(self, other):
        if isinstance(other, Person):
            return self.age > other.age
        return NotImplemented

person1 = Person("Alice", 30)
person2 = Person("Bob", 25)

print(person1 < person2)  # False
print(person1 > person2)  # True

In this example, the __lt__() and __gt__() methods compare two Person instances based on their ages. Note that the methods return the special NotImplemented value when the comparison is not supported (e.g., when comparing a Person instance with an integer).

Conclusion

In this blog post, we have explored different ways to compare strings in Python, including the use of comparison operators, built-in functions, and special methods. We have also discussed some practical examples and tips to help you better understand the concepts. When comparing strings in Python, it's essential to keep in mind the lexicographic order and the case sensitivity of the comparisons. Depending on your needs, you can choose the appropriate methods and techniques to compare strings and achieve the desired results.