Comparing Python strings is a common everyday pro­gram­ming task used to interpret user input, check huge data sets, or work with text-based protocols. We’ll show you several ways to compare strings in Python and provide un­der­stand­able examples.

Operators and functions to compare strings in Python

Python provides users with a whole set of compare string operators and pre-built functions that make comparing strings easy and fast. First, we’ll look at the com­par­i­son operators and then the com­par­i­son methods. Then, we’ll look at two code examples to show you how the operators and methods work.

Com­par­i­son operators

The easiest way to compare two Python strings is with Python operators. As with integers or floating-point numbers, com­par­i­son operators can be used to check that strings are equal. However, operators in this context don’t work as they do with numbers, as there are several string prop­er­ties that can be compared. The below table provides an overview of com­par­i­son operators and their functions.

Operator De­scrip­tion Example Return value
== Strings are equal "Hello" == "hello" false
!= Strings are not equal "Hello" != "hello" true
< lex­i­co­graph­ic order smaller "Australia" < "Zimbabwe" true
> lex­i­co­graph­ic order larger "Australia" > "Zimbabwe" false
<= lex­i­co­graph­ic order less than or equal to "Germany" <= "United States" false
>= lex­i­co­graph­ic order greater than or equal to "Germany" <= "Germany" true

Here, “lex­i­co­graph­ic order” is the technical term for “al­pha­bet­i­cal order” and means the same thing. Words with a low lex­i­co­graph­ic order come earlier in the alphabet than words with a high lex­i­co­graph­ic order. So, the string “abcd” has a lower lex­i­co­graph­ic order than the string “xyz”.

Empty spaces in strings have the lowest lex­i­co­graph­ic order of all char­ac­ters. So if you take the first char­ac­ters of a string as Python substring, that substring will always have a lower order than the original string. For example, the string “Alex” has a lower lex­i­co­graph­ic order than the string “Alexander”.

Remember that Python’s lex­i­co­graph­ic order doesn’t always coincide with the usual al­pha­bet­ic order. For example, Python evaluates the ex­pres­sion “a < b” as “true”, but the ex­pres­sion “a < B” as “false”. That’s because in both ASCII and Unicode standards, the uppercase letters are always encoded with lower values than the lowercase letters.

Note

In addition to comparing strings, for­mat­ting texts is an important part of pro­gram­ming. In our article on Python string format methods, we look at the most important for­mat­ting methods and operators.

Com­par­i­son methods

In addition to com­par­i­son operators, there are some built-in methods that let you compare strings according to other criteria:

Method De­scrip­tion Example Return value
.startswith() Returns “true” when the first few letters of a string match another string "Benjamin".startswith("Ben") true
.endswith() Returns “true” when the last letters of a string match another string "Benjamin".endswith("jasmin") false
.find() Returns index of the first oc­cur­rence of a substring; if the substring does not occur, -1 is returned. "Christmas".find("mas") 4

Code example when comparing strings in Python

To show you how the above operators and methods work, we’ll introduce you to two examples. One of them is easy while the other is a bit more complex.

Check whether the list is sorted al­pha­bet­i­cal­ly

In this example, the program creates a list out of input text. It then uses com­par­i­son operators to check if the list is sorted al­pha­bet­i­cal­ly.

input_list = []
while(True):
    temp = input('Please enter your word. If you don’t want to type any more words, enter \'.\'')
    if temp == '.':
        break
    input_list.append(temp)
print('Your entry: ', input_list)
i = 0
alph = 1
while(i < len(input_list) - 1):
    if(input_liste[i] > input_list[i + 1]):
        print('This list is not sorted alphabetically!')
        alph = 0
        break
    i = i + 1
if(alph == 1):
    print('This list is sorted alphabetically.')
Python

Person database with search function

In this more complex example, the user is asked to enter people’s surnames and first names. These are each inserted into a list, which in turn is in­te­grat­ed into a larger list. This creates a nested list where each sublist contains a person’s first and last name. This large list is then sorted al­pha­bet­i­cal­ly by surname. Now, the user can enter text again to search for people in the database. This is done by using the com­par­i­son method .find().

# Input
people = []
while(True):
    temp = input('Please enter the person’s last name. If you don’t want to enter people anymore, please enter \'.\')
    if temp == '.':
        break
    person = []
    person.append(temp)
    temp = input('Please enter the person’s first name.')
    person.append(temp)
    people.append(person)
print(Your entry: ', people)
# Sort
people.sort()
print(Sorted: ', people)
# Search function
while(True):
    search = input('Please enter string to browse database. If you don’t want to search for people anymore, please enter \'.\'')
    if search == '.':
        break
    for i in people:
        if(i[0].find(search) != -1 or i[1].find(search) != -1):
            print('Match found: ', i[0], ', ', i[1])
Python
Tip

Want to get your web ap­pli­ca­tion online quickly and without much effort? No problem! Deploy Now from IONOS could be the perfect solution for you.

Go to Main Menu