Python String Equals: How to Use Python String Comparison
The equal operator is used to compare two strings. It compares one by one character of both strings. When different characters are found in string, then their Unicode value is compared. In Python, the character with a lower Unicode value is considered to be smaller, and a higher Unicode value considered to be higher.
Python String Equals
Python String comparison can be performed using equal (==) and comparison (<, >, !=, <=, >=) operators. There are no particular functions to compare two strings in Python. Strings in python are contiguous series of characters delimited by single or double-quotes. Python doesn’t have any separate data type for characters, so they are represented as a single character string.
See the following code.
# app.py lead = 'Millie' print(lead == 'Millie') print(lead == 'millie')
➜ pyt python3 app.py True False ➜ pyt
Their Unicode values are different; that is why the second output is False.
That means the Python equals operator is case sensitive.
How to get Unicode values of characters in Python
Well, you can use the Python ord() function to get the Unicode values of characters in Python.
# app.py print(ord('m')) print(ord('M')) print(ord('a')) print(ord('A'))
➜ pyt python3 app.py 109 77 65 97 ➜ pyt
In the above section’s example, where we compare the strings “Millie” and “millie“, the Unicode values of m and M are different; that is why we got the False in output because they are not the same despite the same character their case sensitiveness matters.
Take input from User
We can use the Python input() function to take input from the user and then compare the values using the Python comparison operators.
See the following example.
# app.py mando = input('Please enter the name of mando:\n') lando = input('Please enter the name of lando:\n') if mando < lando: print(mando + " comes before " + lando + " in the dictionary.") elif mando > lando: print(mando + " comes after " + lando + " in the dictionary.") else: print(mando + " and " + lando + " are same.")
➜ pyt python3 app.py Please enter the name of mando: harry Please enter the name of lando: potter harry comes before potter in the dictionary. ➜ pyt
The h comes first before p.
What if one of the string is made of the second string with some additional characters? Well, Let’s find out what will be the output in that case.
# app.py print('Hot' < 'Hotpie')
➜ pyt python3 app.py True ➜ pyt
If the characters sequence is the same in both the strings but one of them has some extra characters, then the larger length string is considered greater than the smaller one.
Python string equals operator always checks for the Unicode value of characters of String, and if they are matched, then it will return True otherwise, it returns False.
Finally, Python String Equals Example is over.