文字列の比較と検索
「特定の単語が含まれているか?」「文字が一致しているか?」という判定は、条件分岐(if文)などで多用します。
1. 含まれているか判定する:in
text = "Pythonは楽しい言語です"
print("Python" in text) # 含まれている
print("Java" in text) # 含まれていない
print("Java" not in text) # not inで「含まれない」を判定
▶ 出力結果
True False True
2. 完全一致の判定:==
input_pw = "pass123"
correct_pw = "pass123"
print(input_pw == correct_pw) # 一致
print(input_pw == "password") # 不一致
▶ 出力結果
True False
大文字と小文字は区別されることに注意しましょう。
3. 大文字小文字を無視して比較する
user_input = "Admin"
registered = "admin"
# そのまま比較:区別される
print(user_input == registered)
# lower()で小文字に統一してから比較
print(user_input.lower() == registered.lower())
▶ 出力結果
False True
