Compare Two Strings in Python

Compare Two Strings in Python
Compare Two Strings in Python

In this article, we'll see how to compare two strings in Python. We'll look at three different ways to do this: using the == Operator, using the is Keyword, and using the cmp() function. Let's get started!

Comparing strings in Python is an ordinary operation for many developers. For example, you might want to check if a user's inputted password is correct before allowing them to log in to your application. Or you might want to see if two files have the same contents before deciding whether or not to overwrite one of them.

In any case, comparing strings is a fundamental skill that all Python developers should know how to do.

In this article, we'll look at three different ways to compare strings in Python. We'll start with the most basic method: using the == Operator.

The == Operator

The first way to compare two strings is using the Equality (==) Operator. It's the most common way to compare strings in Python.

To use the == Operator, place it between two strings that you want to compare:

if string_one == string_two:

    # do something

If the two strings are equal, the condition will evaluate to True, and the code inside the if block will execute. If the strings are not equal, the condition will evaluate to False, and the code inside the if block will be skipped.

Let's try it out with a few examples. First, we'll compare two identical strings:

print('hello' == 'hello')
Output:
True

As you can see, since these two strings are exactly alike, the == Operator returns True.

Now let's try comparing two different strings:

print('hello' == 'goodbye')
Ouput:
False

Since these two strings are not equal, the == Operator returns False.

It's important to note that the == Operator is case-sensitive. This means that if you compare two strings, those strings' capitalization will be taken into account. For example:

print('Hello' == 'hello')
Output:
False

In this case, even though the strings have the same characters and in the correct order, they're not considered equal because the string casing is not similar.

Strings with similar letters but different casing are regarded as different strings. This is based on Unicode character comparison.

We can compare two strings in Python using other comparison operators as well. I.e., They work similarly to the == Operator.

Operator Functionality.
== equal to
!= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to

Now that we've learnt how to use the == Operator to compare strings, let's look at another way: using the is Keyword.

The is Keyword

The second way to compare two strings is by using the is Keyword. This method is very similar to the == Operator:

if string_one is string_two:

    # do something

If the two strings are equal, the condition will evaluate to True, and the code inside the if block executes. If the strings are not equal, the condition evaluates to False, and the code inside the if block will be skipped.

Let's try it out with a few examples. First, we'll compare two identical strings:

print('hello' is 'hello')
Output:
Returns True

Just like with the == Operator, since these two strings are exactly alike, the "is" Keyword returns True.

Now let's try comparing two different strings:

print('hello' is 'goodbye')
Output
False

Again, since these two strings are unequal, the Keyword returns False.

The difference between the "==" Operator and the "is" Keyword.

So what's the difference between using == and is to compare strings? The answer has to do with how Python handles memory. When you create a string in Python, that string is stored in memory. For example:

my_string = 'hello world'

The string 'hello world' is stored in memory, and the variable my_string references that location in memory.

When you use the == Operator to compare two strings, Python checks to see if the characters in those strings are equal. However, when you use the is Keyword to compare two strings, Python checks to see if those strings are stored in the same location in memory.

In most cases, this won't make a difference. However, there are cases where it matters. For example:

s = 'Hello world'
t = s
s is t
Output:
True

In this case, we create a string called s and assign it the value 'Hello world'. Then we create another string called t and give it the value of s. Since both variables reference the same string in memory, using the is Keyword returns True.

However, if we were to modify the string stored in s, that would not change the string stored in t:

s = 'Hello world'
t = s
s += '!'
t is s
Output:
False

In this case, we create a string called s and assign it the value 'Hello world'. Then we create another string called t and assign it the value of s. Finally, we modify the string stored in s by adding an exclamation point to the end of it. Even though both variables are referencing the same location in memory, since we've changed the string stored in that location, using the is Keyword returns False.

So which method should you use when comparing strings? In most cases, it doesn't matter. However, if you're working with many strings or worried about memory usage, it's best to use the == Operator.

The cmp() function

The cmp() function is a built-in function in Python 2.x that allows you to compare two strings. The syntax for the cmp() function is as follows:

cmp(str_a, str_b)

The cmp() function returns an integer value. If the return value is less than 0, str_a is less than str_b. If the return value is greater than 0, str_a is greater than str_b. If the return value is 0, str_a is equal to str_b.

Let's see how the cmp() function works in practice. We'll compare two strings: "Hello" and "World":

print(cmp("Hello", "World"))
Output:
-15

The output of this code is -15. It means that, according to the cmp() function, "Hello" is less than "World".

You might wonder why the output is a -15 and not just a - It turns out that the cmp() function uses lexicographical order when comparing strings.

Lexicographical order is alphabetical, but it also considers uppercase and lowercase letters. In lexicographical order, upper case letters come before lower case letters. So, "Hello" is less than "world", even though "h" comes after "w" in the alphabet.

If you want to compare two strings without considering lexicographical order, you can use the == Operator.

Conclusion

In this article, we've gone over how to compare two strings in Python. We've seen how to use the == Operator, the is Keyword to compare strings, and how to use the cmp() function.

Questions???, put them in the comments.

Happy coding :)

If you enjoy our content, please consider buying us a coffee to support our work:

Table of Contents
Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.