介绍
您可以使用平等(==
)和比较(<
, >
, !=
, <=
, >=
)运算符来比较Python中的字符串。
Python 字符串比较将两个字符串中的字符比较一个接一个,当发现不同的字符时,它们的 Unicode 代码点值就会被比较。
Python 平等和比较运算器
声明字符串变量:
1fruit1 = 'Apple'
下表显示了使用不同的运算符比较相同的字符串(Apple
到Apple
)的结果。
Operator | Code | Output |
---|---|---|
Equality | print(fruit1 == 'Apple') | True |
Not equal to | print(fruit1 != 'Apple') | False |
Less than | print(fruit1 < 'Apple') | False |
Greater than | print(fruit1 > 'Apple') | False |
Less than or equal to | print(fruit1 <= 'Apple') | True |
Greater than or equal to | print(fruit1 >= 'Apple') | True |
两个字符串是完全相同的,换句话说,它们是平等的,等式运算符和其他等式运算符返回True
。
如果你比较不同值的字符串,那么你会得到完全相反的输出。
如果您比较包含相同字符串的字符串,例如苹果
和ApplePie
,则较长的字符串被认为是更大的。
使用运营商比较用户输入以评估平等
此示例代码采集并比较用户的输入,然后程序使用比较的结果来打印有关输入字符串的字母顺序的额外信息,在这种情况下,程序假定较小的字符串先于较大的字符串。
1fruit1 = input('Enter the name of the first fruit:\n')
2fruit2 = input('Enter the name of the second fruit:\n')
3
4if fruit1 < fruit2:
5 print(fruit1 + " comes before " + fruit2 + " in the dictionary.")
6elif fruit1 > fruit2:
7 print(fruit1 + " comes after " + fruit2 + " in the dictionary.")
8else:
9 print(fruit1 + " and " + fruit2 + " are the same.")
以下是输入不同值时的潜在输出示例:
1[secondary_label Output]
2Enter the name of first fruit:
3Apple
4Enter the name of second fruit:
5Banana
6Apple comes before Banana in the dictionary.
以下是输入相同字符串时的潜在输出示例:
1[secondary_label Output]
2Enter the name of first fruit:
3Orange
4Enter the name of second fruit:
5Orange
6Orange and Orange are the same.
<$>[注]
**注:**本示例要工作,用户需要输入两个输入字符串的第一个字母的上一个案例或只有下一个案例,例如,如果用户输入苹果
和香蕉
字符串,那么输出将是苹果在字典中是香蕉之后的香蕉
,这是错误的。
这种差异是因为上级字母的 Unicode 代码点值总是小于下级字母的 Unicode 代码点值:a 的值为 97 和 B 的值为 66. 您可以通过使用 `ord() 函数 来自行测试这些字符的 Unicode 代码点值。
结论
在本文中,您了解如何使用平等(==
)和比较(<
, >
, !=
, <=
, >=
)运算符来比较Python中的字符串。