String Comparison in Python with Example

In Python or any other programming language, string comparison means identifying whether or not two strings are equivalent to each other.

In this tutorial, we will learn how to compare two strings in Python with the help of the best examples.

Basically, Python provides us three general ways by which we can compare between two strings. They are as:

  • Using relational operators
  • Using is and is not
  • User-defined function

Python String Comparison using Relational Operators


We can compare two strings with the standard relational or comparison operators. These relational operators use ASCII or Unicode value of the characters of strings to compare two strings.

In other words, relational operators use standard character by character comparison rules for ASCII or Unicode. ASCII values of numbers, uppercase and lowercase letters are as:

  • Numbers (0 to 9) are from 48 to 57.
  • Uppercase (A to Z) are from 65 to 90.
  • Lowercase (a to z) are from 97 to 122.

Relational operators return a boolean value, True or False, according to the operator used. Following are the relational operators available in Python programming language.

  • Operator (==): This “equal to” operator checks whether or not two strings are equal.
  • Operator (!=): This “not equal” operator checks if two strings are not equal.
  • Operator (>): This “greater than” operator checks if the string on its left side is greater than that on its right side.
  • Operator (<): This “less than” operator checks if the string on its left side is smaller than that on its right side.
  • Operator (>=): This “greater than or equal to” operator checks if the string on its left side is greater than or equal to that on its right side.
  • Operator (<=): This “less than or equal to” operator checks if the string on its left side is smaller than or equal to that on its right side.

Let’s take an example program to understand the concept of comparison operators for string.

Example 1:

# Python program to compare two strings using comparison operators.
str1 = 'january'
str2 = 'jane'
print(str1 == str2)
print(str1 != str2)
print(str1 > str2)

print(str1 >= str2)
print(str1 < str2)
print(str1 <= str2)
Output:
      False
      True
      True
      True
      False
      False

We can compare strings using various comparison or relational operators. For example, we can use the double equal sign (==) operator for string equality. For string inequality, use (!=) sign.


In the above example program, we have created two strings “january” and “jane” and stored in variables named str1 and str2, respectively.

(a) For operation str1 == str2: Python interpreter compares the first two characters (j and j) of both strings. As their ASCII values are equal, the second two characters (a and a) using their ASCII values compare. Because they are also equal, the third two characters (n and n) compare.

Since they are also equal, the fourth characters (u and e) compare. As they are not equal because of different ASCII values of both characters. Therefore, str1 == str2 returns false value.

(b) For operation str1 != str2: Since both strings are not equal, it returns true value.

(c) In case of str1 > str2: After comparing the third characters of both strings, Python compares the fourth characters (u and e) of strings. As ‘u’ has greater ASCII value than ‘e’, str1 is greater than str2. Therefore, str1 > str2 operation returns true value. Similarly, for str1 >= str2.

(d) For str1 < str2 and str1 <= str2: Since the ASCII value of ‘u’ is neither smaller nor equal to the ASCII value of ‘e’, both operations return false value.


Example 2:

# Python program to compare two strings using comparison operators.
print('abc' == 'abc')
print('abc' != 'abc')
print('a' == 'A')

print('a' != 'A')
print('abc' > 'ABC') 
print('1234' > '4567')
Output:
      True
      False
      False
      True
      True
      False

(a) ‘abc’ == ‘abc’: It returns true because letter case are same.

(b) ‘abc’ != ‘abc’): It returns false because letter case are same.

(c) ‘a’ == ‘A’: It returns false because letter case are different.

(d) ‘a’ != ‘A’: It returns true because letter case are different.

(e) ‘abc’ > ‘ABC’: It returns false because ASCII values for lowercase letters are greater than ASCII values for uppercase letters.


(f) ‘1234’ > ‘4567’: It returns false because ASCII values of 1234 is lower than 4567.


Example 3:

Let’s take an example in which we will compare a string against an empty string.

# Python program to compare a string with an empty string.
str1 = 'Python'
str2 ='' # an empty string.
print(str1 == str2)
print(str1 > str2)
print(str1 < str2)
print(str1 != str2)
Output:
      False
      True
      False
      True

Example 4:

str1 = 'abc'
str2 =' abc' # space before letters in the string.
print(str1 == str2)
print(str1 > str2)
print(str1 < str2)
print(str1 != str2)
Output:
      False
      True
      False
      True

Example 5:

Let’s write a program to compare username and password and display the message “login successful”. In this scenario, we will take username and password as input from the user.

username = 'John123'
password = 'jo1234#'
user = input('Enter your username: ')
if username == user:
    passw = input('Enter your password: ')
    if password == passw:
        print('Login successful')
    else:
        print('You have entered wrong password.')
else:
    print('You have entered wrong username.')
Output:
      Enter your username: John123
      Enter your password: jo1234#
      Login successful

Comparing String using Identity Operators


In Python, we can also compare two strings with the help of identity operators. Python supports two types of identity operators. They are:
is and is not.

This type of special operators checks whether or not both operands refer to the same object. Let’s take an example to understand this concept.

Example 6:

# Python program to compare two strings using identity operators.
str1 = 'Python'
str2 ='Python'
str3 = str1

# Comparing two strings using is and is not operators. 
print(str1 is str1)
print(str1 is str2)
print(str1 is str3)

print(str1 is not str2)
print(str1 is not str2)
print(str1 is not str3)
Output:
      True
      True
      True
      False
      False
      False

In this example, str1, str2, and str3 are string objects with the same values. Therefore, they are equal, identical, and stored in the same memory location. Hence, ‘is’ identity operator returned true value and ‘is not’ operator returned false value.

Example 6:

str1 = '1234'
str2 = '1234'
if str1 is str2:
    print('Both strings are identical.')
else:
    print('Both strings are not identical.')
Output:
       Both strings are identical.

Example 7:

str1 = 'abcd'
str2 = input('Enter a string "abcd": ')
print(str1 is str2)

str3 = 'pqrs'
str4 = input('Enter a string "pqrs": ')
print(str3 is not str4)
Output:
      Enter a string "abcd": abcd
      False
      Enter a string "pqrs": pqrs
      True

In this example, the statement print(str1 is str2) returns false value because both are referring to the different string objects in different memory locations instead of having the same value.

Similarly, the statement print(str3 is not str4) returns true value because both are referring to the different string objects in different memory locations instead of having the same value.

Comparing String using User-defined Function


In Python, we can also create a user-defined function to compare strings. A user-defined function compares two strings based upon the number of digits. Let’s take an example of it to understand the concept clearly.

Example 8:

# Python program to compare two strings based on the number of digits.
def string_comp(str1, str2):
    count1 = 0
    count2 = 0
  # Find the length of strings using len() function.
    len_str1 = len(str1)
    len_str2 = len(str2)

    for i in range(len_str1):
        if str1[i] >= "0" and str1[i] <= "9": 
            count1 += 1 # increment by 1. 

    for i in range(len_str2): 
        if str2[i] >= "0" and str2[i] <= "9":
            count2 += 1 # increment by 1.
    return count1 == count2 # comparing.

# Mian program.
# Calling function by passing argument values.
print(string_comp("1234", "1234"))
print(string_comp('345', '1234'))
print(string_comp('Scientech', 'Scientech'))
Output:
       True
       False
       True

In this tutorial, you have learned about string comparison in Python with various example programs. Hope that you will have understood how to compare strings in Python and practiced all example programs.
Thanks for reading!!!

⇐ PrevNext ⇒

Please share your love