Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ 文字列の比較 | 異なる型間の相互作用
Pythonのデータ型

book文字列の比較

メニューを表示するにはスワイプしてください

Pythonにおける文字列の比較は、デフォルトで大文字と小文字を区別します。ユーザー入力が大文字・小文字の違いや余分な空白を含む可能性がある場合は、比較前に正規化を行います。信頼性の高い方法としては、空白を削除し、大文字・小文字を統一してから等価性や接頭辞・接尾辞のチェックを行います。

大文字・小文字を区別する場合と区別しない場合

デフォルトでは、"Apple" == "apple"False となります。大文字・小文字を無視するには、両方を正規化します。

12345
# Comparing two email addresses entered with different letter cases email_saved = "Support@Codefinity.com" email_entered = "support@codefinity.COM" print(email_saved.lower() == email_entered.lower()) # True → emails match regardless of case
copy

casefold() は、lower() よりも強力で国際対応のバリアントであり、大文字・小文字を区別しない比較のデフォルトとして推奨される方法。

12345
# Comparing international usernames regardless of letter case username_db = "straße" username_input = "STRASSE" print(username_db.casefold() == username_input.casefold()) # True → matches even with special characters
copy

トリムして比較

ユーザーが誤ってスペースを追加することが多い。比較前に先頭と末尾の空白を削除。

12345
# Validating a user's role input from a form user_input = " admin " required_role = "ADMIN" print(user_input.strip().casefold() == required_role.casefold()) # True → matches after cleanup and case normalization
copy

接頭辞と接尾辞のチェック

startswithendswith を使用。大文字小文字を区別しないチェックには、事前に正規化を行う。

123456789
# Checking if the uploaded document has the correct format and name uploaded_file = "Report_Final.PDF" # Validate file type (case-insensitive) print(uploaded_file.lower().endswith(".pdf")) # True → valid PDF file # Validate file name prefix (e.g., all reports start with "rep") required_prefix = "rep" print(uploaded_file.strip().casefold().startswith(required_prefix.casefold())) # True → matches prefix ignoring case
copy

一貫した正規化パイプライン

シンプルで再現性のある順序を選択:

  1. .strip()で外側の空白を除去;
  2. .casefold()(または好みに応じて.lower())で大文字・小文字を標準化;
  3. その後、==instartswithendswithなどの比較を実行。

1. どの行が大文字・小文字を区別しない等価性チェックを正しく実行していますか?

2. s = " Hello " の場合、前後の空白を無視して True と大文字・小文字を区別せず等価性チェックを行い、"hello" を返す式はどれですか?

3. 堅牢な大文字・小文字を区別しない比較に最も適した記述はどれですか?

question mark

どの行が大文字・小文字を区別しない等価性チェックを正しく実行していますか?

正しい答えを選んでください

question mark

s = " Hello " の場合、前後の空白を無視して True と大文字・小文字を区別せず等価性チェックを行い、"hello" を返す式はどれですか?

正しい答えを選んでください

question mark

堅牢な大文字・小文字を区別しない比較に最も適した記述はどれですか?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 4.  2

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 4.  2
some-alt