検索と測定
メニューを表示するにはスワイプしてください
文字列の一部を読み取れるようになったら、次のステップはその内容について質問することです。「この文字列が含まれているか?」「どこにあるか?」「何回現れるか?」「特定の文字列で始まる/終わるか?」などです。
メンバーシップ
in を使うと、部分文字列が文字列内のどこかに現れるかどうかを確認できます。結果はブール値で返されます。
12345# Checking if a user's bio mentions specific skills user_bio = "Experienced in Python programming and data analysis." print("Python" in user_bio) # True → the bio mentions Python print("Java" not in user_bio) # True → Java is not listed as a skill
位置の検索
find(sub)は最初に一致した部分の開始インデックスを返し、見つからない場合は -1 を返す;rfind(sub)は右側から検索し、最後に一致したインデックス(または -1)を返す;index(sub)はfindと同様だが、部分文字列が存在しない場合はValueErrorを発生させる。
12345678# Searching for keywords inside a product description description = "This brand new bracelet is made from recycled materials." print(description.find("bra")) # 5 → first occurrence of "bra" print(description.rfind("bra")) # 15 → only one "bra" found print(description.find("gold")) # -1 → not found, returns -1 print(description.index("bra")) # 5 → same as find(), but raises an error if not found print(description.index("gold")) # ValueError → "gold" not in the text
出現回数のカウント
count(sub) は部分文字列が重複しない回数だけ出現する数を返す。
12345# Counting occurrences of words or letters in a customer review review = "Amazing banana smoothie with banana slices on top!" print(review.count("banana")) # 2 → the word appears twice print(review.count("a")) # 8 → letter 'a' appears multiple times
開始と終了
文字列の開始や終了を確認するには、startswith または endswith を使用。これらは、はい/いいえの答えだけが必要な場合、スライスよりも明確で安全。
12345# Checking if the uploaded file has the correct name and format uploaded_file = "report_final.pdf" print(uploaded_file.startswith("report")) # True → file name starts correctly print(uploaded_file.endswith(".pdf")) # True → valid file format for upload
大文字・小文字を区別しないチェック
文字列メソッドは大文字・小文字を区別します。大文字・小文字を区別しない検索を行うには、両方を .lower()(または .upper())で正規化します。
12345# Checking a user's message for a polite greeting user_message = "Hello, team! Let's start the meeting." print("hello" in user_message.lower()) # True → greeting detected print(user_message.lower().startswith("hello")) # True → message begins with "hello"
1. このコードの出力は何ですか?
2. 部分文字列が存在しない場合にエラーを発生させない文はどれですか?
3. s = "Banana" のとき、接頭辞 True を大文字・小文字を区別せずに判定して "ba" を返す式はどれですか?
すべて明確でしたか?
フィードバックありがとうございます!
セクション 3. 章 3
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 3. 章 3