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:
- Greater than
- less than
- greater than or equal to
- Less than or equal to
- ==: is equal to
- !=: 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”.