Tutorial

How To Compare Strings in Python

Updated on December 22, 2022
authorauthor

Pankaj and Andrea Anderson

How To Compare Strings in Python

Introduction

You can compare strings in Python using the equality (==) and comparison (<, >, !=, <=, >=) operators. There are no special methods to compare two strings. In this article, you’ll learn how each of the operators work when comparing strings.

Python string comparison compares the characters in both strings one by one. When different characters are found, then their Unicode code point values are compared. The character with the lower Unicode value is considered to be smaller.

Python Equality and Comparison Operators

Declare the string variable:

fruit1 = 'Apple'

The following table shows the results of comparing identical strings (Apple to Apple) using different operators.

Operator Code Output
Equality print(fruit1 == 'Apple') True
Not equal to print(fruit1 != 'Apple') False
Less than print(fruit1 < 'Apple') False
Greater than print(fruit1 > 'Apple') False
Less than or equal to print(fruit1 <= 'Apple') True
Greater than or equal to print(fruit1 >= 'Apple') True

Both the strings are exactly the same. In other words, they’re equal. The equality operator and the other equal to operators return True.

If you compare strings of different values, then you get the exact opposite output.

If you compare strings that contain the same substring, such as Apple and ApplePie, then the longer string is considered larger.

Comparing User Input to Evaluate Equality Using Operators

This example code takes and compares input from the user. Then the program uses the results of the comparison to print additional information about the alphabetical order of the input strings. In this case, the program assumes that the smaller string comes before the larger string.

fruit1 = input('Enter the name of the first fruit:\n')
fruit2 = input('Enter the name of the second fruit:\n')

if fruit1 < fruit2:
    print(fruit1 + " comes before " + fruit2 + " in the dictionary.")
elif fruit1 > fruit2:
    print(fruit1 + " comes after " + fruit2 + " in the dictionary.")
else:
    print(fruit1 + " and " + fruit2 + " are the same.")

Here’s an example of the potential output when you enter different values:

Output
Enter the name of first fruit: Apple Enter the name of second fruit: Banana Apple comes before Banana in the dictionary.

Here’s an example of the potential output when you enter identical strings:

Output
Enter the name of first fruit: Orange Enter the name of second fruit: Orange Orange and Orange are the same.

Note: For this example to work, the user needs to enter either only upper case or only lower case for the first letter of both input strings. For example, if the user enters the strings apple and Banana, then the output will be apple comes after Banana in the dictionary, which is incorrect.

This discrepancy occurs because the Unicode code point values of uppercase letters are always smaller than the Unicode code point values of lowercase letters: the value of a is 97 and the value of B is 66. You can test this yourself by using the ord() function to print the Unicode code point value of the characters.

Conclusion

In this article you learned how to compare strings in Python using the equality (==) and comparison (<, >, !=, <=, >=) operators. Continue your learning about Python strings.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author


Default avatar

Technical Editor


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
May 17, 2021

what if I want to get the difference in term of percentage.For instance , Apple and apple instead of getting false can I get a percentage of similarity like 93%

- Ahmed

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    February 18, 2021

    You missed one thing, if it’s ‘applebanana’ and ‘appleorange’ then ‘appleorange’ is greater than ‘applebanana’. Hopefully, this helps.

    - Akash

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      February 17, 2021

      when comparing strings, is only unicode of first letter considered or addition of unicodes of all the letters is considered?

      - BS

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        November 5, 2020

        print(‘Apple’ < ‘ApplePie’) does not return True because of the length. print(‘2’ < ‘11’) will return False.

        - Ammar S Salman

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          May 2, 2020

          your day of love may bring the gratitude of others for life.

          - Hobbes.Christine

            Try DigitalOcean for free

            Click below to sign up and get $200 of credit to try our products over 60 days!

            Sign up

            Join the Tech Talk
            Success! Thank you! Please check your email for further details.

            Please complete your information!

            Become a contributor for community

            Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

            DigitalOcean Documentation

            Full documentation for every DigitalOcean product.

            Resources for startups and SMBs

            The Wave has everything you need to know about building a business, from raising funding to marketing your product.

            Get our newsletter

            Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

            New accounts only. By submitting your email you agree to our Privacy Policy

            The developer cloud

            Scale up as you grow — whether you're running one virtual machine or ten thousand.

            Get started for free

            Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

            *This promotional offer applies to new accounts only.