How to compare 2 strings in Python?

In this short tutorial, let us look at the various string comparison methods in python. We also look at the various edge cases, limitations and caveats.

Table of Contents

  • Python String Comparison
  • String Comparison Operators
  • "==" and "!="
  • "is" and "not is"
  • Limitations and Caveats

Python String Comparison

Python string comparison methods are used to compare strings. However, Python also comes with a few handy inbuilt operators to facilitate this. However before we dive into the methods, we have an important concept that needs to be addressed.

Data in your program are represented as objects, and object has these 3 properties. Identity (Id) - Identity contains the address of the memory in which the data is stored. Next, Type is the data type of the object and Value is the content that the object stores.

Python saves memory by re-using object IDs containing the same value; eg: . This also makes python string comparison faster and easier. Also, please be vary these terms as each operator uses a property to compare objects., this makes python string comparison much faster and easier.

String Comparison Operators

Out of the different methods that can be used to compare strings in python, I've explained two of the most commonly used methods below.

Note: All these comparison methods return a boolean true or false.

Python strings comparison using "==" and "!=":

The == and != are commonly used relation operations for python string comparison. These operators compare Unicode values of all the elements in the string and return either a boolean true or false.

Unicode values are python's way of storing string. Each element of a string is given a Unicode, this helps keep elements uniform irrespective of the language the programmer uses. You can read more about this here.

So these relation operators compare strings based on their Unicode values.

Using "=="

The "==" is a python string comparison method that checks if both the values of the operands are equal. This operator is the most commonly used method to check equality in python.

s1 = 'flexiple!'
print(id(s1))
#Output = 2621679855024
s2 = 'flexiple!'
print(id(s2))
#Output = 2621679855024
s3 = 'flexiple'
print(id(31))
#Output = 140735453670112

print(s1==s2)
#output = True
print(s2==s3)
#output = False

The operator returns True and False respectively. Also notice how the Id of s1 and s2 is identical.

However, bear in mind that the Id function will return a different number based on you compiler.

Using "!="

The != is another python string comparison operator that checks if the values of the operands are not equal. It performs the opposite of == operator. The code snippet below is the implementation of the same.

s1 = 'flexiple!'

s2 = 'flexiple!'

s3 = 'flexiple'

print(s1!=s2)
#Output = False
print(s2!=s3)
#Output = True

Python strings comparison using "is" and "not is"

The is and not is operators are quite similar to == and != respectively. However, unlike the relational operators, is and is not compares to the Identity (id) of the objects and returns true if they share the same identity.

One could argue that the identity of the object remains the same, but this is not the case when working with immutables. When the object is given another value the memory allocates changes giving it a new identity.

When crafting the logic in your code, you may want to execute different commands depending on the similarities or differences between two or more strings.

In this article, we'll see various operators that can help us check if strings are equal or not. If two strings are equal, the value returned would be True. Otherwise, it'll return False.

How to Check for String Equality in Python

In this section, we'll see examples of how we can compare strings using a few operators.

But before that, you need to have the following in mind:

  • Comparisons are case sensitive. G is not the same as g.
  • Each character in a string has an ASCII value (American Standard Code for Information Interchange) which is what operators look out for, and not the actual character. For example, G has an ASCII value of 71 while g has a value of of 103. When compared, g becomes greater than G.

How to Compare Strings Using the == Operator

The == operator checks if two strings are equal. Here is an example:

print("Hello" == "Hello")
# True

We got a value of True returned because both strings above are equal.

Let's make it look a bit more fancy using some conditional logic:

string1 = "Hello"
string2 = "Hello"

if string1 == string2:
    print("Both strings are equal")
else:
    print("Both strings are not equal")
    
# Both strings are equal

In the code above, we created two strings and stored them in variables. We then compared their values. If these values are the same, we would get one message printed to the console and if they aren't the same, we would have a different message printed.

Both strings in our case were equal, so we had "Both strings are equal" printed. If we changed the first string to "hello", then we would have a different message.

Note that using

string1 = "Hello"
string2 = "Hello"

if string1 == string2:
    print("Both strings are equal")
else:
    print("Both strings are not equal")
    
# Both strings are equal
2 would make the interpreter assume you want to assign one value to another. So make sure you use == for comparison.

How to Compare Strings Using the string1 = "Hello" string2 = "Hello" if string1 == string2: print("Both strings are equal") else: print("Both strings are not equal") # Both strings are equal4 Operator

The

string1 = "Hello"
string2 = "Hello"

if string1 == string2:
    print("Both strings are equal")
else:
    print("Both strings are not equal")
    
# Both strings are equal
4 operator checks if two strings are not equal.

string1 = "Hello"
string2 = "Hello"

if string1 != string2:
    print("Both strings are not equal") # return if true
else:
    print("Both strings are equal") # return if false
    
# Both strings are equal

We're using the same example but with a different operator. The

string1 = "Hello"
string2 = "Hello"

if string1 == string2:
    print("Both strings are equal")
else:
    print("Both strings are not equal")
    
# Both strings are equal
4 is saying the strings are not equal which is False so a message is printed based on those conditions.

I have commented the code to help you understand better.

How to Compare Strings Using the string1 = "Hello" string2 = "Hello" if string1 == string2: print("Both strings are equal") else: print("Both strings are not equal") # Both strings are equal8 Operator

The

string1 = "Hello"
string2 = "Hello"

if string1 == string2:
    print("Both strings are equal")
else:
    print("Both strings are not equal")
    
# Both strings are equal
8 operator checks if one string is smaller than the other.

print("Hello" < "hello")

# True

This returns True because even though every other character index in both strings is equal, H has a smaller (ASCII) value than h .

We can also use conditional statements here like we did in previous sections.

How to Compare Strings Using the string1 = "Hello" string2 = "Hello" if string1 != string2: print("Both strings are not equal") # return if true else: print("Both strings are equal") # return if false # Both strings are equal1 Operator

The

string1 = "Hello"
string2 = "Hello"

if string1 != string2:
    print("Both strings are not equal") # return if true
else:
    print("Both strings are equal") # return if false
    
# Both strings are equal
1 operator checks if one string is less than or equal to another string.

print("Hello" <= "Hello")

# True

Recall that this operator checks for two things – if one string is less or if both strings are the same – and would return True if either is true.

We got True because both strings are equal.

How to Compare Strings Using the string1 = "Hello" string2 = "Hello" if string1 != string2: print("Both strings are not equal") # return if true else: print("Both strings are equal") # return if false # Both strings are equal5 Operator

The

string1 = "Hello"
string2 = "Hello"

if string1 != string2:
    print("Both strings are not equal") # return if true
else:
    print("Both strings are equal") # return if false
    
# Both strings are equal
5 operator checks if one string is greater than another string.

print("Hello" > "Hello")

# False

Since the string on the left isn't greater than the one on the right, we got False returned to us.

How to Compare Strings Using the string1 = "Hello" string2 = "Hello" if string1 != string2: print("Both strings are not equal") # return if true else: print("Both strings are equal") # return if false # Both strings are equal8 Operator

The

string1 = "Hello"
string2 = "Hello"

if string1 != string2:
    print("Both strings are not equal") # return if true
else:
    print("Both strings are equal") # return if false
    
# Both strings are equal
8 operator checks if one string is greater than or equal to another string.

print("Hello" >= "Hello")

# True

Since one of both conditions of the operator is true (both strings are equal), we got a value of True.

Conclusion

In this article, we learned about the various operators you can use when checking the equality of strings in Python with examples. We also saw how case sensitivity can alter the equality of strings.

Happy coding!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT


How to compare 2 strings in Python?
Ihechikara Vincent Abba

This author's bio can be found in his articles!


If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

How do you check if two strings are similar in Python?

Python strings equality can be checked using == operator or __eq__() function. Python strings are case sensitive, so these equality check methods are also case sensitive.

Can I use == to compare two strings?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

How do you compare 2 strings?

We compare the strings by using the strcmp() function, i.e., strcmp(str1,str2). This function will compare both the strings str1 and str2. If the function returns 0 value means that both the strings are same, otherwise the strings are not equal.