String Comparison in Python

Techwalla may earn compensation through affiliate links in this story.

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 "value1 operator value2." When making comparisons, you can use strings within quotes or use variables with string values.


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.


Video of the Day

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 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 uppercase letters are less than lowercase 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 uppercase or lowercase 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."