How to Compare Strings in Python?

Python – Compare Strings

To compare strings in Python, we can use Python Relational Operators.

  • To check if two strings are equal, use equal to operator.
  • To check if a string appears prior to other if sorted in order, use less than operator.
  • To check if a string appears after the other if sorted in order, use greater than operator.

In this tutorial, we will go through each of the scenarios, and finally write a function that compares two strings.

1. Check if two given strings are equal

In this example, we will compare two strings and check if they are equal using equal to operator.

Python Program

str1 = 'abcd'
str2 = 'abcd'

if str1 == str2 :
    print('Both the strings are equal.')
else :
    print('Both the strings are not equal.')
Run Code Copy

Output

Both the strings are equal.

2. Check if given string is greater than other string

In this example, we will take two strings: str1 and str2; and check if the string str1 is greater than the other string str2 using greater than operator.

Python Program

str1 = 'cde'
str2 = 'abc'

if str1 > str2 :
    print('str1 is greater than str2.')
else :
    print('str1 is not greater than str2.')
Run Code Copy

Output

str1 is greater than str2.

3. Check if given string is less than other string

In this example, we will take two strings: str1 and str2; and check if the string str1 is less than the other string str2 using less than operator.

Python Program

str1 = 'abc'
str2 = 'cde'

if str1 < str2 :
    print('str1 is less than str2.')
else :
    print('str1 is not less than str2.')
Run Code Copy

Output

str1 is less than str2.

4. Write a function that compares two given strings

Now, we will write a function that accepts two strings as parameters and compares them. The function returns zero if the strings are equal, negative value if first string is less than the second string and positive value if first string is greater than the second string.

Function

def compare(str1, str2):
    if str1 == str2 :
        return 0
    elif str1 > str2 :
        return 1
    else :
        return -1

Let us write a Python program that uses this function, and compares two strings.

Python Program

def compare(str1, str2):
    if str1 == str2 :
        return 0
    elif str1 > str2 :
        return 1
    else :
        return -1

str1 = 'abc'
str2 = 'cde'
result = compare(str1, str2)
if result == 0 :
    print('Both the strings are equal.')
elif result > 0 :
    print('str1 is greater than str2.')
elif result < 0 :
    print('str1 is less than str2.')
Run Code Copy

Output

str1 is less than str2.

Summary

In this tutorial of Python Examples, we learned how to compare two strings.

Related Tutorials

Code copied to clipboard successfully 👍