Python String Comparison: A Complete Guide

In Python, you can use comparison operators to compare the size of strings. Some commonly used comparison operators include:

  1. Greater than
  2. less than
  3. greater than or equal to
  4. Less than or equal to
  5. ==: is equal to
  6. !=: not equal to

The sample code is as follows:

str1 = "apple"
str2 = "banana"

if str1 < str2:
    print("str1 小于 str2")
elif str1 > str2:
    print("str1 大于 str2")
else:
    print("str1 等于 str2")

When running the above code, it will output that str1 is less than str2 because in the alphabet, “a” comes before “b”.

bannerAds