Python Python Trim String Example

How to compare strings in Python


In this article, you are going to learn about how to compare strings in Python.

In general, a string is nothing but a sequence of multiple characters. In the Python programming language, strings are an array of bytes that represent Unicode characters. In the journey of development, we often need to work with strings and compare them. To compare strings in Python, we may use relational operators and some inbuilt methods. In this article, we will discover how we can compare strings by using them in python.

Equal and Not Equal

We can use an equal operator to compare whether two strings are the same or not and also use a not equal operator for checking if the strings are not equal. See the below code example:

string1 = 'Hello'
string2 = 'Hello'

#Using Double Equal operator
print(string1 == string2)

#using Not Equal Opereator
print(string1 != string2)

# Output:
# True
# False

Here, you can see that we are getting boolean value true for the first case because the strings are equal and for this reason, we are getting boolean value false when we have used the not equal operator.

Note: Strings are case-sensitive. That means if you declare two strings with the same value but in different cases then it will return false.

Greater than and Less than

We can also compare strings with the greater than and less than operators and check while the strings are big or small from one another. Here, these operators will compare the strings on the basis of the Unicode value. See the below code example:

string1 = 'Hello'
string2 = 'hello'

#Using Double Equal operator
print(string1 > string2)

#using Not Equal Opereator
print(string1 < string2)

# Output:
# False
# True

Here, you can see that we are getting the boolean value false because the Unicode value of H is 72 and the Unicode value of h is 104. As a result, it considered string1 as small. On the other hand, it returns true when we compared string2 is greater than string1 or not.

Is and Is Not

You can also use is or is not for comparing strings in python. This is similar to equal and the not equal operator. Let’s see the below code example:

string1 = 'Hello'
string2 = 'hello'

#Using "is"
print(string1 is string2)

#using "is not"
print(string1 is not string2)

# Output:
# False
# True

Here, you can see that we are getting boolean value false even if the stings are the same. The reason behind it is that they are not in the same case. And we are getting boolean values false as they are not equal.

These are some useful approaches and you may follow them for comparing strings in the Python programming language.


Share on social media

//