How to compare strings in Python

Comparing Python strings is a common everyday programming 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 understandable 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 comparison operators and then the comparison methods. Then, we’ll look at two code examples to show you how the operators and methods work.

Comparison operators

The easiest way to compare two Python strings is with Python operators. As with integers or floating-point numbers, comparison 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 properties that can be compared. The below table provides an overview of comparison operators and their functions.

Operator Description Example Return value
== Strings are equal "Hello" == "hello" false
!= Strings are not equal "Hello" != "hello" true
< lexicographic order smaller "Australia" < "Zimbabwe" true
> lexicographic order larger "Australia" > "Zimbabwe" false
<= lexicographic order less than or equal to "Germany" <= "United States" false
>= lexicographic order greater than or equal to "Germany" <= "Germany" true

Here, “lexicographic order” is the technical term for “alphabetical order” and means the same thing. Words with a low lexicographic order come earlier in the alphabet than words with a high lexicographic order. So, the string “abcd” has a lower lexicographic order than the string “xyz”.

Empty spaces in strings have the lowest lexicographic order of all characters. So if you take the first characters 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 lexicographic order than the string “Alexander”.

Remember that Python’s lexicographic order doesn’t always coincide with the usual alphabetic order. For example, Python evaluates the expression “a < b” as “true”, but the expression “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, formatting texts is an important part of programming. In our article on Python string format methods, we look at the most important formatting methods and operators.

Comparison methods

In addition to comparison operators, there are some built-in methods that let you compare strings according to other criteria:

Method Description 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 occurrence 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 alphabetically

In this example, the program creates a list out of input text. It then uses comparison operators to check if the list is sorted alphabetically.

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 integrated 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 alphabetically by surname. Now, the user can enter text again to search for people in the database. This is done by using the comparison method .find().

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 application online quickly and without much effort? No problem! Deploy Now from IONOS could be the perfect solution for you.

Was this article helpful?
We use cookies on our website to provide you with the best possible user experience. By continuing to use our website or services, you agree to their use. More Information.
Page top