We can compare strings in python. So, how can we do python string comparison? We can compare python strings with different signs like equality (==) and comparison (<, >, <=, >= , !=) operators.
Here, the comparison of the strings is done through unicode values. The lower unicode value is considered to be smaller.
Let’s do an example for string comparison and see the return of the python code for differetn situations.
msg = 'Abc'
print(msg == 'Abc')
print(msg != 'Abc')
print(msg < 'Abc')
print(msg > 'Abc')
print(msg <= 'Abc')
print(msg >= 'Abc')
The return of this python code will be like below:
True
False
False
False
True
True
You can also learn How to Split Python Strings.
The first code returns true and the second code returns false, because the strings are same and equal. The third and fourt codes will return false and the last two codes will return true. Because the last two one has also equal sign.
For different purposes, you can use python string comparison in your python codes. With this functions, you can compare the strings and get returns about these strings. You can increase these examples by yourself to understant this comparison lesson better.
Leave a Reply