String Comparison in Python

In the previous article we discussed some of the frequent string operations, now let us look at comparing the values or characters of strings. Python allows various different comparison operators to be allowed for this purpose.

Operators for String Comparison in Python

Let us examine a program using comparison operators:

s1="Codekyro"
s2="ide"
print(s1<s2)
print(s1<=s2)
print(s1>s2)
print(s1>=s2)
print(s1==s2)
print(s1!=s2)
Output:
True
True
False
False
False
True

How does the comparison of alphabetical characters occur? As we discussed earlier, each alphabet has it’s own integer representation in the commonly used UNICODE standard. In other languages, ASCII code is usually used to represent the alphabetical string characters.

The characters with higher integer representation are taken as having higher values, hence the values increase as we go down the alphabetical ordering. Let us have a deeper look through the use of the ord( ) function.

s1="a"
s2="b"
s3="c"
print(s1>s2)
print(s2<s3)

#Determine the integer values of a,b and c through use of ord( )
print(ord(s1))
print(ord(s2))
print(ord(s3))
Output:
False
True
97
98
99

The first comparison results in false as the value of s2(98) is greater than that of s1(97), while the second comparison results in True as s2(98) is less than s3(98).

Moreover the string with greater number of characters is also taken to be higher in value or weightage unless the string characters it is being compared to has higher value.

s1="abc"
s2="abcd"
s3="ABC"
s4="x"

print(s2>s1)
print(s3>s4)
Output:
True
False

Capitalized or lower case alphabets each have their separate number value depending upon the case.

s1="abc"
s2="ABC"

print(ord('A'))
print(ord('a'))
print(s1>s2)
Output:
65
97
True

Here s1 represents a higher value than it’s capitalized counterpart s1, because the capitalized letter A starts from the 65 range, while lower case letters begin at 97 with a. In the next article, we will examine Pattern Searching in Python.


Leave a Comment