String Comparison in Python | str() and ord()

String Comparison in Python

In this blog, we will take a look at String Comparison in Python.

A String is a series of characters, bound by quotes. Python allows us to use both single and double quotes for a string in python.


“This is a string.”

The quotes also acts as the delimiter for a string.

Learn Python OpenCV – Give vision to your computer.

String Comparison in Programming

String Comparison is a common task that we humans do very easily, but programming languages see strings differently.

Each Character in the string has an Unicode value. Programming languages understand the Unicode values and treat the Unicode value as string.

While Comparing Strings, the programming language compares the Unicode value of each string one by one. If all the character matches it returns true, else false.

Python String Comparision

Python seems easy because of its simplicity. we can use numerical comparision for strings and thus we don’t have to remember any extra function for comparing strings.

String Comparison in Python can be done using the logical operators as the number comparison is done i.e using ==, !=, >,<,<=, or >=.

String Comparison Example in Python:

name = 'Divyanshu Shekhar'

print(name == 'Divyanshu Shekhar')
print(name != 'Divyanshu Shekhar')
print(name < 'Divyanshu Shekhar')
print(name > 'Divyanshu Shekhar')
print(name >= 'Divyanshu Shekhar')
print(name <= 'Divyanshu Shekhar')

New String Using str() in Python

A New String can be created (instantiated) using the str() inbuilt function into python.

String created using the str() function, hold a None value i.e NULL.

str1 = str()
str2 = str()

print(str1 == str2)
print(str1 == "")

Passing String into the str() function.

str1 = str("DS")
str2 = str("DR")

print(str1 == str2)
print(str1 == "")

Lexicographic Comparison Python

This section is to prove that python compares string, by comparing each character one by one.

str1 = str("DS")
str2 = str("DR")

print(str1 > str2, ord(str1[0]), ord(str1[1]))
print(str1 < str2, ord(str2[0]), ord(str2[1]))
True 68 83
False 68 82

In the above code both the string’s first character is same, and both has the ASCII value of 68. In Python we can get the ASCII value of characters and numbers using the ord() function.

The Second Character varies in each string, the first one containes ‘S’, and the second one ‘R’. As we know character ‘R’ comes before ‘S’ when compared lexicographically. Python compares both characters ASCII code and then decides which string is greater than or less than the other.

That’s all about it.

Learn more about python from official documentation.


Leave a Reply

Your email address will not be published. Required fields are marked *