介绍
您可以使用Python中的等式(==
)和比较(<
、>
、!=
、<=
、>=
)运算符来比较字符串。没有专门用于比较两个字符串的特殊方法。在本文中,您将学习在比较字符串时每个运算符的工作原理。
Python字符串比较逐个比较两个字符串中的字符。当找到不同的字符时,它们的Unicode代码点值会被比较。具有较低Unicode值的字符被认为是较小的。
Python等式和比较运算符
声明字符串变量:
fruit1 = '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
。
如果比较具有不同值的字符串,则会获得完全相反的输出。
如果您比较包含相同子字符串的字符串,例如Apple
和ApplePie
,那么较长的字符串被视为较大。
使用运算符比较用户输入以评估相等性
这个示例代码接受并比较用户的输入。然后程序使用比较的结果来打印有关输入字符串字母顺序的附加信息。在这种情况下,程序假定较小的字符串在较大的字符串之前。
fruit1 = input('Enter the name of the first fruit:\n')
fruit2 = input('Enter the name of the second fruit:\n')
if fruit1 < fruit2:
print(fruit1 + " comes before " + fruit2 + " in the dictionary.")
elif fruit1 > fruit2:
print(fruit1 + " comes after " + fruit2 + " in the dictionary.")
else:
print(fruit1 + " and " + fruit2 + " are the same.")
这是输入不同值时潜在输出的示例:
OutputEnter the name of first fruit:
Apple
Enter the name of second fruit:
Banana
Apple comes before Banana in the dictionary.
这是输入相同字符串时潜在输出的示例:
OutputEnter the name of first fruit:
Orange
Enter the name of second fruit:
Orange
Orange and Orange are the same.
注意:为了使此示例有效,用户需要输入两个输入字符串的第一个字母要么全部大写,要么全部小写。例如,如果用户输入字符串apple
和Banana
,则输出将是apple comes after Banana in the dictionary
,这是不正确的。
这种差异是由于大写字母的 Unicode 代码点值始终小于小写字母的 Unicode 代码点值而引起的:`a` 的值是 97,`B` 的值是 66。您可以使用 `ord()` 函数打印字符的 Unicode 代码点值来自行测试。
结论
在本文中,您学习了如何使用 Python 中的等式(`==`)和比较(`<`、`>`、`!=`、`<=`、`>=`)运算符来比较字符串。继续学习关于Python 字符串。
Source:
https://www.digitalocean.com/community/tutorials/python-string-comparison