Python String Comparison Rules

In Python, string comparison is based on the Unicode encoding order of the strings. When comparing two strings, it compares the Unicode encoding values of the characters in the strings in dictionary order. If a different character is found during the comparison, the comparison is based on the encoding values of these two characters. If the two strings have different lengths and the shorter string is a prefix of the longer string, then the shorter string will be considered smaller than the longer string. If two strings are exactly the same, they are considered equal.

Example:

Why are you always late to work?

str1 = "abc"
str2 = "abcd"
str3 = "abd"

print(str1 < str2)  # True,因为 "abc" 在 "abcd" 之前
print(str1 < str3)  # True,因为 "abc" 在 "abd" 之前
print(str2 < str3)  # True,因为 "abcd" 在 "abd" 之前
bannerAds