For comparing two strings in Python you can use relational operators (==, <, <=, >, >=, !=). Using these operators content of the Strings is compared in lexicographical order and boolean value true or false is returned.
Note that for equality comparison use ‘==’
not 'is'
operator as 'is' operator does the identity comparison (compares the memory location of the String objects).
Python String comparison
When Strings are compared in Python, comparison is done character by character.
Checking for equality using ‘==’
def check_equality(str1, str2): #using string slicing str = str1[8: :] print('String is ',str) if str == str2: print('Strings are equal') else: print('Strings are not equal') str1 = "This is Python" str2 = "Python" check_equality(str1, str2)
Output
String is Python Strings are equal
In the example using Python string slicing, a slice of the string is obtained which is then compared with another string for equality.
If you use ‘is’ operator, comparison returns false even if the content is same as in that case memory location of the objects is compared.
def check_equality(str1, str2): #using string slicing str = str1[8: :] print('String is', str) if str is str2: print('Strings are equal') else: print('Strings are not equal') str1 = "This is Python" str2 = "Python" check_equality(str1, str2)
Output
String is Python Strings are not equal
Python String comparison examples
Let’s see another example with other operators.
def check_equality(str1, str2): if str1 > str2: print(str1, 'is greater than', str2) if str1 < str2: print(str1, 'is less than', str2) if str1 != str2: print(str1, 'is not equal to', str2) str1 = "This" str2 = "That" check_equality(str1, str2)
Output
This is greater than That This is not equal to That
In the example following condition
if str1 < str2: print(str1, 'is less than', str2)
returns false so the message accompanying this condition is not displayed.
That's all for this topic Comparing Two Strings in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Python Tutorial Page
Related Topics
You may also like-