Python | 字符串比较 (Python | String comparison)
In python programming language, strings can be compared using the relationship/ comparisons operators like ==, !=, <, >, <=, >=.
在python编程语言中,可以使用诸如== , != , < , > , <= , > =之类的关系/比较运算符来比较字符串。
These operators need two operands (strings), checks the characters (based on its UNICODE values) of the string and return True or False.
这些运算符需要两个操作数(字符串),检查字符串的字符(基于其UNICODE值)并返回True或False 。
Example 1:
范例1:
str1 = 'IncludeHelp'
# comparison
print("str1 == \'IncludeHelp\'): ", str1 == 'IncludeHelp')
print("str1 != \'IncludeHelp\'): ", str1 != 'IncludeHelp')
print("str1 < \'IncludeHelp\'): ", str1 < 'IncludeHelp')
print("str1 <= \'IncludeHelp\'): ", str1 <= 'IncludeHelp')
print("str1 > \'IncludeHelp\'): ", str1 > 'IncludeHelp')
print("str1 >= \'IncludeHelp\'): ", str1 >= 'IncludeHelp')
Output
输出量
str1 == 'IncludeHelp'): True
str1 != 'IncludeHelp'): False
str1 < 'IncludeHelp'): False
str1 <= 'IncludeHelp'): True
str1 > 'IncludeHelp'): False
str1 >= 'IncludeHelp'): True
Example 2:
范例2:
str1 = 'IncludeHelp'
str2 = 'includehelp'
# comparison
print("str1 == str2: ", str1 == str2)
print("str1 != str2: ", str1 != str2)
print("str1 < str2: ", str1 < str2)
print("str1 <= str2: ", str1 <= str2)
print("str1 > str2: ", str1 > str2)
print("str1 >= str2: ", str1 >= str2)
Output
输出量
str1 == str2: False
str1 != str2: True
str1 < str2: True
str1 <= str2: True
str1 > str2: False
str1 >= str2: False
Example 3:
范例3:
str1 = 'IncludeHelp'
str2 = 'includehelp'
str3 = 'IncludeHelp'
if str1 == str2:
print(str1, "is equal to", str2)
else:
print(str1, "is not equal to", str2)
if str3 == str3:
print(str3, "is equal to", str3)
else:
print(str3, "is not equal to", str3)
Output
输出量
IncludeHelp is not equal to includehelp
IncludeHelp is equal to IncludeHelp
Example 4:
范例4:
# input two strings
str1 = input("Enter string 1: ")
str2 = input("Enter string 2: ")
# comparing
if str1 < str2:
print(str1, "comes before", str2)
elif str1 > str2:
print(str1, "comes after", str2)
else:
print(str1, "and", str2, "are same")
Output
输出量
RUN 1:
Enter string 1: Honda Amaze
Enter string 2: Honda City
Honda Amaze comes before Honda City
RUN 2:
Enter string 1: BMW
Enter string 2: Audi
BMW comes after Audi
RUN 3:
Enter string 1: BMW z4
Enter string 2: BMW z4
BMW z4 and BMW z4 are same
翻译自: https://www.includehelp.com/python/string-comparison.aspx