介紹
您可以使用相等性 (==
) 和比較 (<
, >
, !=
, <=
, >=
) 運算符在 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