String Comparison in Python (Complete Guide)

In this Python tutorial, let us discuss Python compare strings. We will see various examples of python comparing two strings.

There are 9 methods to compare strings in Python, which are shown below:

  • Using the == operator
  • Using the is operator
  • Using the cmp function
  • Using the strcoll function
  • Using the user-defined method
  • Using the !=
  • Using the SquenceMatcher
  •  Using the < operator
  • Using the > operator

Python String Comparison

Here we will see multiple methods to compare two strings in Python. However, let us start with the first method in Python.

Method-1: Using the == operator

You can use the == operator to check if two strings are equal in Python.

string1 = "USA"
string2 = "USA"

# Compare string1 and string2 for equality
if string1 == string2:
    print("The strings are equal")
else:
    print("The strings are not equal")

The code defines two string variables string1 and string2, both with the value “USA”. It then checks if the two strings are equal using the == operator.

  • If the two strings are equal, the program will print “The strings are equal”, otherwise it will print “The strings are not equal”. Since the two strings are indeed equal, the output will be “The strings are equal”.
Output: The strings are equal

Read: Python string formatting

Method-2: Using the is operator

You can use the is an operator to check if two strings are the same object in memory.

string1 = "United Kingdom"
string2 = "UNITED KINGDOM"

# Check if string1 and string2 refer to the same string in memory
if string1 is string2:
    print("The strings are the same string")
else:
    print("The strings are not the same string")

The above code defines two string variables, string1 and string2, with different capitalizations. It then uses the is operator to check if the two strings are the same object in memory.

Output: The strings are not the same string

Read: Python split string by space

READ:  Python Program to Find Product of Three Numbers [3 Methods]

Method-3: Using the cmp function

The cmp function returns -1 if the first string is less than the second, 0 if they are equal, and 1 if the first string is greater than the second.

def cmp(a, b):
    return (a > b) - (a < b) 
    
string1 = "Brazil"
string2 = "Brazil"

# Compare string1 and string2 using the cmp() function
if cmp(string1, string2) == 0:
    print("The strings are equal")
elif cmp(string1, string2) < 0:
    print("The first string is less than the second")
else:
    print("The first string is greater than the second")

The code above defines a cmp() function which takes two arguments and returns 1 if the first argument is greater than the second, -1 if it’s less than the second, and 0 if they are equal.

  • It uses the cmp() function to compare string1 and string2, and prints out a message based on the result.

Read: Find Last Number in String in Python

Method-4: Using the strcoll function

The strcoll function is similar to cmp, but takes into account locale-specific rules for string comparison.

import locale

# Set the locale to en_US.UTF-8
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')

# Define two string variables, string1 and string2
string1 = "cafe"
string2 = "caff"

# Use the strcoll() function to compare string1 and string2
if locale.strcoll(string1, string2) == 0:
    print("The strings are equal")
elif locale.strcoll(string1, string2) < 0:
    print("The first string is less than the second")
else:
    print("The first string is greater than the second")

The code above imports the locale module, which provides a way to handle locale-specific data, such as dates, times, and currency formats.

  • The code then sets the locale to en_US.UTF-8 using the setlocale() function. It defines two string variables, string1 and string2, and uses the strcoll() function to compare them.
Python string comparison using the strcoll function
Python string comparison using the strcoll function

Read: Find first number in string in Python

Method-5: Using the user-defined method

We are going to create a function that takes two strings as arguments and returns True if they are equal (case-insensitive) or False otherwise.

# Define a function to compare two strings while ignoring case
def string_compare(str1, str2):
    if str1.lower() == str2.lower():
        return True
    else:
        return False

# Call the string_compare() function with "Canada" and "canada" as arguments
result = string_compare("Canada", "canada")

# Print the result
print(result) 

The above code defines a function string_compare() that compares two strings, str1 and str2, while ignoring the case. The function returns True if the two strings are equal, ignoring case, and False otherwise.

  • The string_compare() function is called with “Canada” and “Canada” as arguments, and the resulting boolean value is assigned to the result variable. Finally, the value of the result is printed on the console.
READ:  Python create empty set | How to create empty set in Python

Read: Remove character from string Python

Method-6: Using the !=

The != operator is used to check if two values are not equal to each other. In the context of strings, you can use != to check if two strings are not equal to each other.

# Define two strings with the same value
string1 = "USA"
string2 = "USA"

# Compare the two strings for inequality
if string1 != string2:
    # If the strings are not equal, print a message
    print("The two strings are not equal")
else:
    # If the strings are equal, print a different message
    print("The two strings are equal")

In the above code, the != operator is used to check if string1 is not equal to an empty string. Since “hello” is not an empty string, the output of this code would be “The string is not empty”.

Output: The two strings are equal

Read: How to trim a string in Python

Method-7: Using the SquenceMatcher

You can use the SequenceMatcher class from the difflib module to compare two strings and find the similarity between them.

# Import the difflib module
import difflib

# Define two strings to be compared
string1 = "apple"
string2 = "applesauce"

# Create a SequenceMatcher object to compare the strings
s = difflib.SequenceMatcher(None, string1, string2)

# Get the similarity between the two strings
similarity = s.ratio()

# Print the similarity to the console
print(f"The similarity between the two strings is {similarity:.2f}")

The above code imports the difflib module and uses it to compare the similarity of two strings, string1, and string2.

  • A SequenceMatcher object is created with the two strings as arguments, and the ratio() method is called on this object to get the similarity score between the strings. The resulting value is stored in the similarity variable.
  • Finally, the similarity value is printed to the console using an f-string with a precision of 2 decimal places.
Output: The similarity between the two strings is 0.67

Read: Lower function in Python string

READ:  How to create a new file in Python [2 different ways]

In this case, the similarity between “apple” and “applesauce” is 0.67, indicating that the two strings are somewhat similar but not identical.

Method-8: Using the < operator

The < operator performs a lexicographic (dictionary) comparison between the two strings, meaning that it compares the characters in the strings from left to right and returns True if the first string is less than the second string.

# Define two string variables
name1 = 'Python good'
name2 = 'Python is good'

# Compare the strings and print the result
if name1 < name2:
    print(name1,'is less than',name2)

The above code defines two string variables, name1 and name2. It then uses an if statement to compare the two strings using the less-than operator (<).

Method-9: Using the > operator

The > operator performs a lexicographic (dictionary) comparison between the two strings, meaning that it compares the characters in the strings from left to right and returns True if the first string is greater than the second string.

# Define two string variables
name1 = 'Python is good'
name2 = 'Python good'

# Compare the strings and print the result
if name1 > name2:
print(name1,'is greater than',name2)
Output: Python is good is greater than Python good

You may also like to read the following Python tutorials.

In this Python tutorial, we learned about, Python compare strings using the following methods:

  • Using the == operator
  • Using the is operator
  • Using the cmp function
  • Using the strcoll function
  • Using the user-defined method
  • Using the !=
  • Using the SquenceMatcher
  •  Using the < operator
  • Using the > operator