Compare strings in Python: A Step-by-Step Guide | Hostman (2024)

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."

Operator

Name

Example

==

Equal

'dog' == 'cat'

Comparison result:

False

!=

Not equal

'dog' != 'cat'

Comparison result:

True

>

Greater than

'dog' > 'cat'

Comparison result:

True

<

Less than

'dog' < 'cat'

Comparison result:

False

>=

Greater than or equal to

'dog' >= 'cat'

Comparison result:

True

<=

Less than or equal to

'dog' <= 'cat'

Comparison result:

False

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:

ord(character)

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}")
else:
print(f "The strings {first_string} and {second_string} are the same!")

In this code, we read two character sequences using theinput() 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:

string.upper()
string.lower()

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.

Compare strings in Python: A Step-by-Step Guide | Hostman (1)

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:

first_string.__eq__(second_string)

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))
else:
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:
Washington
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:

source_string.startswith(pattern)
source_string.endswith(pattern)

Here's an example:

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

print(example_string.startswith("String"))
print(example_string.endswith("method")))

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

Compare strings in Python: A Step-by-Step Guide | Hostman (2)

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.

Conclusion

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.

Compare strings in Python: A Step-by-Step Guide | Hostman (2024)
Top Articles
Quali sono le materie prime maggiormente scambiate?
Editorial: Why artificial intelligence can’t replace journalism – as explained by Google’s AI
Ohio Houses With Land for Sale - 1,591 Properties
Dte Outage Map Woodhaven
Stretchmark Camouflage Highland Park
Identifont Upload
DENVER Überwachungskamera IOC-221, IP, WLAN, außen | 580950
EY – все про компанію - Happy Monday
Acts 16 Nkjv
When Is the Best Time To Buy an RV?
Used Wood Cook Stoves For Sale Craigslist
Nier Automata Chapter Select Unlock
6813472639
Price Of Gas At Sam's
使用 RHEL 8 时的注意事项 | Red Hat Product Documentation
Invert Clipping Mask Illustrator
Effingham Bookings Florence Sc
Strange World Showtimes Near Roxy Stadium 14
Site : Storagealamogordo.com Easy Call
MLB power rankings: Red-hot Chicago Cubs power into September, NL wild-card race
Schedule An Oil Change At Walmart
Adt Residential Sales Representative Salary
Www.publicsurplus.com Motor Pool
What Individuals Need to Know When Raising Money for a Charitable Cause
Harrison County Wv Arrests This Week
Jackie Knust Wendel
27 Modern Dining Room Ideas You'll Want to Try ASAP
Bayard Martensen
Ocala Craigslist Com
Cosas Aesthetic Para Decorar Tu Cuarto Para Imprimir
Korg Forums :: View topic
Till The End Of The Moon Ep 13 Eng Sub
Pch Sunken Treasures
P3P Orthrus With Dodge Slash
Gas Prices In Henderson Kentucky
M3Gan Showtimes Near Cinemark North Hills And Xd
Timothy Kremchek Net Worth
Shoreone Insurance A.m. Best Rating
Cbs Fantasy Mlb
Gasoline Prices At Sam's Club
Walmart Car Service Near Me
M&T Bank
Jane Powell, MGM musical star of 'Seven Brides for Seven Brothers,' 'Royal Wedding,' dead at 92
Wpne Tv Schedule
Dancing Bear - House Party! ID ? Brunette in hardcore action
Rocket League Tracker: A useful tool for every player
8 4 Study Guide And Intervention Trigonometry
17 of the best things to do in Bozeman, Montana
Bradshaw And Range Obituaries
What Time Do Papa John's Pizza Close
Island Vibes Cafe Exeter Nh
Latest Posts
Article information

Author: Lidia Grady

Last Updated:

Views: 6095

Rating: 4.4 / 5 (65 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Lidia Grady

Birthday: 1992-01-22

Address: Suite 493 356 Dale Fall, New Wanda, RI 52485

Phone: +29914464387516

Job: Customer Engineer

Hobby: Cryptography, Writing, Dowsing, Stand-up comedy, Calligraphy, Web surfing, Ghost hunting

Introduction: My name is Lidia Grady, I am a thankful, fine, glamorous, lucky, lively, pleasant, shiny person who loves writing and wants to share my knowledge and understanding with you.