String Comparison in Python

The following are the ways to compare two string in Python:

  1. By using == (equal to) operator
  2. By using != (not equal to) operator
  3. By using sorted() method
  4. By using is operator
  5. By using Comparison operators

1. Comparing two strings using == (equal to) operator

str1 = input("Enter the first String: ")
 
str2 = input("Enter the second String: ")
 
if str1 == str2:
 
    print ("First and second strings are equal and same")
 
else:
 
    print ("First and second strings are not same")

Output:

Enter the first String: AA
Enter the second String: AA
First and second strings are equal and same


2. Comparing two strings using != (not equal to) operator

str1 = input("Enter the first String: ")
 
str2 = input("Enter the second String: ")
  
if str1 != str2:
 
    print ("First and second strings are not equal.")
 
else:
 
    print ("First and second strings are the same.")

Output:

Enter the first String: ab
Enter the second String: ba
First and second strings are not equal.


3. Comparing two strings using the sorted() method

If we wish to compare two strings and check for their equality even if the order of characters/words is different, then we first need to use sorted() method and then compare two strings.

str1 = input("Enter the first String: ")
 
str2 = input("Enter the second String: ")
 
if sorted(str1) == sorted(str2):
 
    print ("First and second strings are equal.")
 
else:
 
    print ("First and second strings are not the same.")

Output:

Enter the first String: Engineering Discipline
Enter the second String: Discipline Engineering
First and second strings are equal.

4. Comparing two strings using ‘is’ operator

Python is Operator returns True if two variables refer to the same object instance.

str1 = "DEED"
 
str2 = "DEED"
 
str3 = ''.join(['D', 'E', 'E', 'D'])
 
 
print(str1 is str2)
 
print("Comparision result = ", str1 is str3)

Output:

True
Comparision result = False

In the above example, str1 is str3 returns False because object str3 was created differently.


5. Comparing two strings using comparison operators

input = 'Engineering'

print(input < 'Engineering')
print(input > 'Engineering')
print(input <= 'Engineering')
print(input >= 'Engineering')

Output:

False
False
True
True

The strings are compared lexicographically. If the left operand string comes before the right string, True is returned.


References

  • Python String Comparison