How does Python compare strings using comparison operators?

0130

In Python, strings can be compared using comparison operators such as ==, !=, <, >, <=, and >=. Here’s how each operator works for string comparison:

  1. Equal to (==): Checks if two strings are identical.

    print("hello" == "hello")  # True
    print("hello" == "world")  # False
  2. Not equal to (!=): Checks if two strings are different.

    print("hello" != "world")  # True
    print("hello" != "hello")  # False
  3. Less than (<): Compares strings lexicographically (dictionary order).

    print("apple" < "banana")  # True
    print("banana" < "apple")  # False
  4. Greater than (>): Also compares strings lexicographically.

    print("banana" > "apple")  # True
    print("apple" > "banana")  # False
  5. Less than or equal to (<=): Checks if one string is less than or equal to another.

    print("apple" <= "banana")  # True
    print("banana" <= "banana")  # True
  6. 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.

0 Comments

no data
Be the first to share your comment!