In Python, strings can be compared using comparison operators such as ==, !=, <, >, <=, and >=. Here’s how each operator works for string comparison:
-
Equal to (
==): Checks if two strings are identical.print("hello" == "hello") # True print("hello" == "world") # False -
Not equal to (
!=): Checks if two strings are different.print("hello" != "world") # True print("hello" != "hello") # False -
Less than (
<): Compares strings lexicographically (dictionary order).print("apple" < "banana") # True print("banana" < "apple") # False -
Greater than (
>): Also compares strings lexicographically.print("banana" > "apple") # True print("apple" > "banana") # False -
Less than or equal to (
<=): Checks if one string is less than or equal to another.print("apple" <= "banana") # True print("banana" <= "banana") # True -
Greater than or equal to (
>=): Checks if one string is greater than or equal to another.print("banana" >= "apple") # True print("apple" >= "banana") # False
Example
Here’s a complete example demonstrating string comparisons:
str1 = "apple"
str2 = "banana"
str3 = "apple"
print(str1 == str2) # False
print(str1 != str2) # True
print(str1 < str2) # True
print(str1 > str2) # False
print(str1 <= str3) # True
print(str1 >= str3) # True
You can use these operators to compare any two strings in Python.
