We Value Your Privacy

We and our partners use technology such as cookies on our site to personalise content and ads, provide social media features, and analyse our traffic. Click below to consent to the use of this technology across the web. You can change your mind and change your consent choices at anytime by returning to this site.

Update Consent
Loading ...

String Comparison in Python

Updated March 23, 2017

To compare two or more string values in Python, you use comparison operators. Python does not have any built-in functions for string comparison. When comparing values, Python always returns either "true" or "false" to indicate the result. The format you use is "value 1 operator value 2." When making comparisons, you can use strings within quotes or use variables with string values.

Loading ...

Comparison Operators

Python has several comparison operators you can use to compare two or more string values. You can use comparison operators in loops or conditional statements. Use "==" to check if two strings are equal or "!=" to see if they are not. You can also use ">" to check if the first string is greater than the second or "<" to check for the opposite. Use ">=" to see if it is greater than or equal to, or "<=" to check if it is less than or equal to the second.

Chained Comparisons

Python lets you chain more than one comparison together in the same line. For example, comparing 'a' > 'b' > 'c' is the same as comparing 'a' > 'b' and then 'b' > 'c' right after. Python returns "true" if all of the comparisons in the chain return true and "false" if any one does not return true. When a comparison does evaluate to false, Python does not compare the rest of the chain.


Python compares all strings lexicographically, which means that "apple" is always less than "banana," which is less than "cherry," and so on. However, string comparisons are case-sensitive. All upper case letters are less than lower case letters. For example, Python determines that "Zebra" is less than "apple." To avoid this confusion when comparing strings lexicographically, temporarily convert all the strings to upper case or lower case and then compare them.

Data Types

When the objects have a different type, Python attempts to convert them to the same time for comparison purposes. For example, comparing a float with the value 10.0 to an integer with the value 10 returns "true" because they are the same. However, an integer with the value 10 is not the same as a string with the value "10" in quotation marks and returns "false." If Python cannot convert values to a common type, it always returns "false."

Loading ...

About the Author

Laura Gittins has been writing since 2008 and is an expert in document design. She has a Bachelor of Science in English, Professional and Technical Writing. She has written education and document design articles for eHow.

Loading ...