Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ 検索と測定 | Strings
Pythonのデータ型

book検索と測定

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

文字列の一部を読み取れるようになったら、次のステップはその内容について質問することです。「この文字列が含まれているか?」「どこにあるか?」「何回現れるか?」「特定の文字列で始まる/終わるか?」などです。

メンバーシップ

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
copy

位置の検索

  • 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
copy

出現回数のカウント

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
copy

開始と終了

文字列の開始や終了を確認するには、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
copy

大文字・小文字を区別しないチェック

文字列メソッドは大文字・小文字を区別します。大文字・小文字を区別しない検索を行うには、両方を .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"
copy

1. このコードの出力は何ですか?

2. 部分文字列が存在しない場合にエラーを発生させない文はどれですか?

3. s = "Banana" のとき、接頭辞 True大文字・小文字を区別せずに判定して "ba" を返す式はどれですか?

question mark

このコードの出力は何ですか?

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

question mark

部分文字列が存在しない場合にエラーを発生させない文はどれですか?

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

question mark

s = "Banana" のとき、接頭辞 True大文字・小文字を区別せずに判定して "ba" を返す式はどれですか?

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

すべて明確でしたか?

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

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

セクション 3.  3

AIに質問する

expand

AIに質問する

ChatGPT

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

セクション 3.  3
some-alt