Log In

How to Compare Python Strings

How to Compare Python Strings
Reading time: 7 min
Hostman Team
Technical writer

Strings in Python are sequences of characters enclosed in quotes. They are used mainly for writing textual information. As with ordinary numbers, character sequences can be compared. However, this process has its peculiarities, which we will discuss later.

This tutorial will break down the possible ways to compare strings in Python and provide illustrative examples for each of them.

Comparison operators 

To compare two strings in Python, you need to learn how the comparison operators work.

In the table below, we will break down the existing comparison operators and give examples to help you understand how they work. In the examples, we will use unequal sequences of characters "dog" and "cat."






'dog' == 'cat'

Comparison result:



Not equal

'dog' != 'cat'

Comparison result:



Greater than

'dog' > 'cat'

Comparison result:



Less than

'dog' < 'cat'

Comparison result:



Greater than or equal to

'dog' >= 'cat'

Comparison result:



Less than or equal to

'dog' <= 'cat'

Comparison result:


All operators in the table return true if the comparison condition is met. In the opposite case, they return false.

In the case of the last four operators in the table, character-by-character comparison is performed. The first characters of each sequence are taken first, then the second characters, and so on. It is also worth considering that identical characters are not equal if they have different cases. So, for example, the symbol "X" will have a lower value than "x". To find out the ordinal value of a character, use the following command:


For example, to find the ordinal value of the letter 'X' with upper case and the letter 'x' with lower case, we can use this:

print('The ordinal value of X = ', ord('X'), '; and x = ', ord('x'))

The output will tell us that X’s ordinal number is 88, while x’s is 120. 

It is also worth mentioning that when comparing two sequences of characters that have the same substring at the beginning (e.g., "Orange" and "Orange Juice"), the larger one will be the one with more characters.

Comparing strings entered from the keyboard

In this chapter, we will compare sequences of characters entered from the keyboard. For this purpose, we will use the comparison operators (==, !=, <, >, <=, >=), explained in the previous chapter.

So, in order to compare two strings in Python entered from the keyboard, let's write the following code:

first_string = input('Enter first string:\n')
second_string = input('Enter the second line:\n')

if first_string > second_string:
    print(f "In the dictionary, the sequence {first_string} is located after the sequence {second_string}")
elif first_string < second_string:
    print(f "In the dictionary, the sequence {first_string} is located before the sequence {second_string}")
    print(f "The strings {first_string} and {second_string} are the same!")

In this code, we read two character sequences using the input() function and then work out all possible cases using the if-elif-else construct. If we try entering different character sequences, say "lake" and "river", the output will tell us that the lake sequence is located before the river sequence.

Now, let's enter the same words but in reverse (first "river" and then "lake”). In this case, the output shows that the river sequence is located before the lake sequence.

Finally, if we enter two identical sequences ("lake" both times), the output will tell us that the sequences are the same.


Case-insensitive string comparison

In the previous sections, we have drawn your attention several times to the importance of case when comparing a sequence of characters. However, this can be circumvented by using the language's built-in methods.

To compare a string to a case-insensitive string in Python, use the string methods upper() and lower(). The first brings a sequence of characters entirely to upper case, and the second to lower case. Their syntax is as follows:


Let's look at how the methods work using an example:

example_string1 = 'orange'
example_string2 = 'ORANGE'

print(example_string1 == example_string2)
print(example_string1.upper() == example_string2)
print(example_string1 == example_string2.lower())

In the example above, we create two string variables and pass them the same values but in different cases. Then, we display three comparison results on the screen. In the first case, we compare the original sequences. In the second, we use the upper() method to convert the first string to upper case and then perform the comparison. And finally, in the third case, we convert the second sequence to lower case.


As you can see from the picture above, in the first case, the character sequences are not equal to each other because they are transmitted with different cases. Still, in the second and third cases, they are equal because of the transformations performed on them.

Using language methods

Let's look at the existing string methods that will help us perform the comparison.

The __eq__ method

The first method is __eq__(). It is equivalent to the == operator, which we considered in the very first chapter of this guide. Its syntax is as follows:


Now, let's use it in an example:

first_string = input('Enter first string:\n')
second_string = input('Enter second string:\n')

If first_string.__eq__(second_string):
    print("The sequences {} and {} are the same!".format(first_string,second_string))
    print("The sequences {} and {} are different!".format(first_string,second_string))

As a result, we get the following:

Enter first string:
New York
Enter second string:
The sequences New York and Washington are different!

The startswith() and endswith() methods

The next two methods are startswith() and endswith(). The former is useful when you want to compare the elements of a Python string located at the beginning of the string against a given character pattern. The latter works the same way but compares to the end of the sequence rather than the beginning.

The syntax for startswith() and endswith() is as follows:


Here's an example:

example_string = "The string is written to test the method"


The result of the code is shown in the image below.

Image5 (1)

Using regular expressions

In addition to the methods and operators discussed above, it is possible to use regular expressions to compare strings in Python.

A regular expression is a specific pattern of characters by which strings are selected. You can create a unique pattern and compare strings or whole text to it. 

As an example, let's create a list containing the names of berries and a regular expression that will be compared to them and return only those sequences that contain the substring "berry" in their names. 

Below, we will write the code to implement the task. You need to import the re module to use regular expressions in your code.

import re

example_list = ['cowberry', 'watermelon', 'cherry', 'blackberry']
expression = re.compile('berry')

for berry in example_list:
    if expression.search(berry):
        print(f"{berry} - this berry contains the substring berry in its name.")

As a result, after comparing the regular expression with the list of berry names, we get the following:

cowberry - this berry contains the substring berry in its name
blackberry - this berry contains the substring berry in its name

As we can see, only two berries fit the filter we created.


In this tutorial, we have demonstrated several ways to compare strings in Python. All of them are unique in their own way, so the choice of the method depends on the specific situation. We hope this guide will make the string comparison in Python much easier for you.