はじめに
Pythonでは、等号(==
)や比較演算子(<
、>
、!=
、<=
、>=
)を使用して文字列を比較することができます。2つの文字列を比較するための特別なメソッドはありません。この記事では、文字列を比較する際に各演算子がどのように動作するかを学びます。
Pythonの文字列比較は、両方の文字列の文字を1つずつ比較します。異なる文字が見つかった場合、それらの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