Pythonで文字列を比較する方法

イントロダクション

Pythonでは、等号(==)や比較演算子(<、>、!=、<=、>=)を使って文字列を比較することができます。文字列を比較するための特別なメソッドはありません。この記事では、文字列を比較する際にそれぞれの演算子がどのように動作するかを学びます。

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.")

異なる値を入力した場合の潜在的な出力の例を示します。

Output

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

同じ文字列を入力した場合の潜在的な出力の一例を以下に示します。 (Onaji mojiretsu o nyūryoku shita baai no senzai-tekina shutsuryoku no irei o ika ni shimasu.)

Output

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

Note

注意:この例が機能するためには、ユーザーが入力文字列の最初の文字に大文字または小文字のいずれかを入力する必要があります。たとえば、ユーザーがappleとBananaと入力した場合、出力はappleがBananaより辞書順で後に来るという誤った結果になります。
この不一致が発生するのは、大文字のUnicodeコードポイントの値が常に小文字のUnicodeコードポイントの値よりも小さいためです。aの値は97であり、Bの値は66です。文字のUnicodeコードポイントの値を出力するために、ord()関数を使用して自分でテストすることができます。

結論

この記事では、Pythonで文字列を等しいかどうか(==)および比較する方法について学びました。Pythonの文字列についての学習を続けてください。

コメントを残す 0

Your email address will not be published. Required fields are marked *


广告
広告は10秒後に閉じます。
bannerAds