Python字符串比较

时间:2020-02-23 14:43:23  来源:igfitidea点击:

可以使用相等(==)和比较(<,>,!=,<=,> =)运算符执行Python字符串比较。
没有比较两个字符串的特殊方法。

Python字符串比较

使用两个字符串中的字符执行Python字符串比较。
两个字符串中的字符被一一比较。
当找到不同的字符时,将比较它们的Unicode值。
Unicode值较低的字符被认为较小。

让我们看一些用于字符串比较的示例。

fruit1 = 'Apple'

print(fruit1 == 'Apple')
print(fruit1 != 'Apple')
print(fruit1 < 'Apple')
print(fruit1 > 'Apple')
print(fruit1 <= 'Apple')
print(fruit1 >= 'Apple')

输出:

True
False
False
False
True
True

两个字符串完全相同,因此它们相等。
因此,在这种情况下,相等运算符将返回True。

让我们看另一个示例,我们将从用户那里获取输入,然后进行比较。

fruit1 = input('Please enter the name of first fruit:\n')
fruit2 = input('Please enter the name of 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 same.")

输出:

Please enter the name of first fruit:
Apple
Please enter the name of second fruit:
Banana
Apple comes before Banana in the dictionary.

Please enter the name of first fruit:
Orange
Please enter the name of second fruit:
Orange
Orange and Orange are same.

让我们看看比较是否区分大小写?另外,如果" a"出现为" A"?

print('apple' == 'Apple')
print('apple' > 'Apple')
print('A unicode is', ord('A'), ',a unicode is', ord('a'))

输出:

False
True
A unicode is 65 ,a unicode is 97

因此,由于其Unicode值," Apple"与" apple"相比要小一些。
我们正在使用ord()函数来打印字符的Unicode代码点值。

如果其中一个字符串由第二个字符串和一些其他字符组成,该怎么办?

print('Apple' < 'ApplePie')

输出:True

如果两个字符串中的字符序列相同,但其中一个具有一些附加字符,则认为长度较大的字符串大于另一个。

如果我们使用<和>运算符比较两个相等的字符串怎么办?

print('apple' < 'apple')
print('apple' > 'apple')

输出:

False
False

显然,两个字符串都不小于也不大于另一个。
因此,在两种情况下输出都是错误的。