how-to-compare-strings-in-python

Python Strings are the standard data types in Python which is the collection of characters surrounded by single quotes, double quotes, or triple quotes.

Single quotes: 'Compare strings "str" in Python'

Double quotes: "Compare strings 'str' in Python"

Triple quotes: '''Compare strings in Python''', """Compare strings in Python"""

In Python, we can compare strings in two ways:

  1. Using Relational operators
  2. Using is & is not keywords

 

1. Using Relational operators

Python strings support the following operators which we can use to compare strings:

relational-operators-python

 

Strings in Python are stored as individual characters i.e. indexed wise. The index by default starts with 0.

As string comparison in Python takes character by character. Whenever we apply any of the above operators while comparing strings. Python compares the Unicode value of each character from the zeroth index to the end of the string.

Based on the operator used, it returns the boolean value either True or False.

forward-backward-indexing-python

Let’s compare the word "PYTHON" & "python".

print("PYTHON" == "python")
print("PYTHON" < "python")
print("PYTHON" <= "python")
print("PYTHON" > "python")
print("PYTHON" >= "python")
print("PYTHON" != "python")

# Output
False
True
True
False
False
True

Note: Python string comparisons are case-sensitive. Same letters in different letter cases(upper/lower) will be treated as separate characters. Thus, for the same character with different letter cases ‘p’ and ‘P’, Python treats them differently.

print('p' == 'P') # False

 

Let’s check how these operators are working using Unicode values.

To calculate the Unicode value of a single string, Python provides a built-in function called ord().

According to the Python definition: ord() return the Unicode code point for a one-character string.

for s in "PYTHON":
    print(s, '-->', ord(s))

print('------------------------------------')

for s in "python":
    print(s, '-->', ord(s))

Output:

P --> 80
Y --> 89
T --> 84
H --> 72
O --> 79
N --> 78
------------------------------------
p --> 112
y --> 121
t --> 116
h --> 104
o --> 111
n --> 110

print(“PYTHON” < “python”) # True

P(80) < p(112)  = True
Y(89) < y(121)  = True
T(84) < t(116)  = True
H(72) < h(104)  = True
O(79) < o(111)  = True
N(78) < n(110)  = True

Here all the conditions are satisfied, and we get the output as True.

Note: string comparisons are done character-wise. So if it fulfills the comparison condition, it moves to the other character in the next position. Otherwise, it returns the value False.

 

2. Using is & is not keywords

In Python, strings can also be compared using is & is not keywords. Not to be confused, is & not are different keywords. We used them in conjunction to have the logic of not equal to as of relational operator(!=).

Basically, == & is a similar kind of logic that checks for equality of two strings, and != & is not checks for inequality between strings. Based on the condition, these keywords either return True or False.

Note: use == when comparing values and is when comparing the identity(id) of the objects.

 

Examples of is & is not

Let’s take two strings called string1 and string2 and apply those keywords as:

String comparison using is

string1 = "Jay Shree Krishna"
string2 = "Jay Shree Krishna"

print(string1 == string2)
print(string1 is string2)

Output:

True
False

From the above output, is returns False in spite values for string1 and string2 variables are the same. So it might be the case of different IDs for string1 and string2.

Let’s check the id of string1 and string2 as:

print(id(string1))
print(id(string2))

Output:

2229251199424
2229265470128

Therefore due to different IDs of the same values, is returns False.

Note: Based on the machine, these IDs could be different.

 

But if variables string1 and string2 contain only a single word, then is returns True in this case.

Let’s take an example:

string1 = "Krishna"
string2 = "Krishna"

print(string1 == string2)
print(string1 is string2)

Output:

True
True

 

String comparison using is not

string1 = "Jay Shree Krishna"
string2 = "Jay Shree Krishna"

print(string1 != string2)
print(string1 is not string2)

Output:

False
True

 

Conclusion

I hope you understand the different strategies for comparing strings in Python. Be careful, when using == & is whenever comparing between strings, use == when working with immutable objects.

Always keep in mind that, string comparison operators can only be used to compare objects of a similar type.

Leave a Reply

Your email address will not be published.