メインコンテンツへスキップ
見出し画像

【Python 100日チャレンジ】Day 17 - 文字列メソッドを扱う

    ユーザーIDを入力するとき、
    「YAMADA@example.com」でも
    「yamada@example.com」でも同じ扱いにしたい──
    こんな場面、実務で本当によくありますよね。

    このような 大文字・小文字の統一、空白の除去、部分一致の検索 など、
    一見めんどくさそうなテキスト処理も、実はほとんど!
    Python が便利な文字列メソッドとして用意してくれています😊

    今日は、
    開発のさまざまな場面で"すぐ使える"
    実用的な文字列メソッドを、わかりやすいサンプルと一緒にサクッと学んでいきましょう!💪
    (15分で読了 ⭐⭐)

    🎯 今日の学習目標

    1. 文字列メソッドとは何かを理解する

    2. 大文字小文字変換メソッドを習得する

    3. 検索/置換メソッドを習得する

    4. 分割/結合メソッドを習得する

    📚 事前知識


    🎯 学習目標 1: 文字列メソッドとは何かを理解する

    文字列メソッドとは?

    文字列メソッド = 文字列オブジェクトに内蔵された便利な機能たち

    文字列は単純なテキストではなく、様々な機能を持つオブジェクトです。Pythonは文字列を扱うための40個以上のメソッドを標準提供しています。

    text = "Hello World"
    print(type(text))  # <class 'str'>
    print(dir(text))   # 使用可能なすべてのメソッドを確認

    メソッドの使い方

    基本構造:「文字列.メソッド名(引数)」

    text = "hello"
    
    # 大文字小文字変換
    print(text.upper())  # HELLO
    
    # 検索
    print(text.find("l"))  # 2
    
    # 置換
    print(text.replace("h", "H"))  # Hello

    元の文字列は変更されない(Immutable)

    重要:文字列は不変(immutable)オブジェクトです。メソッドは常に新しい文字列を返します。

    text = "hello"
    result = text.upper()
    
    print(text)    # hello(元のまま)
    print(result)  # HELLO(新しい文字列)

    主要メソッドのカテゴリ

    大文字小文字系:文字のケース変換

    • upper()、lower()、capitalize()、title()

    検索系:テキスト探索

    • find()、index()、count()、startswith()、endswith()

    判別系:文字列タイプ確認

    • isdigit()、isalpha()、isalnum()、isspace()

    変更系:文字列修正

    • replace()、strip()、lstrip()、rstrip()

    分割/結合系:文字列の分解/組立

    • split()、join()

    🎯 学習目標 2: 大文字小文字変換メソッドを習得する

    基本変換メソッド

    Pythonは5つの大文字小文字変換メソッドを提供します。

    基本変換メソッド:

    • upper():すべて大文字に("hello" → "HELLO")

    • lower():すべて小文字に("HELLO" → "hello")

    • capitalize():最初の文字だけ大文字("hello world" → "Hello world")

    • title():各単語の最初の文字を大文字("hello world" → "Hello World")

    • swapcase():大文字小文字を反転("Hello" → "hELLO")

    upper() - すべて大文字に

    text = "hello world"
    print(text.upper())  # HELLO WORLD
    
    # 実践活用: 大文字小文字を区別しない比較
    user_input = "Yes"
    if user_input.upper() == "YES":
        print("承認されました")

    lower() - すべて小文字に

    text = "HELLO WORLD"
    print(text.lower())  # hello world
    
    # 実践活用: メールアドレスの正規化
    email = "USER@EXAMPLE.COM"
    normalized_email = email.lower()
    print(normalized_email)  # user@example.com

    capitalize() - 最初の文字だけ大文字

    text = "hello world"
    print(text.capitalize())  # Hello world
    
    sentence = "python is fun"
    print(sentence.capitalize())  # Python is fun

    title() - 各単語の最初の文字を大文字

    text = "hello world"
    print(text.title())  # Hello World
    
    # 実践活用: 名前の正規化
    name = "john doe"
    print(name.title())  # John Doe

    swapcase() - 大文字小文字を反転

    text = "Hello World"
    print(text.swapcase())  # hELLO wORLD
    
    # 特殊な使用例
    text = "PyThOn"
    print(text.swapcase())  # pYtHoN

    判別メソッド(大文字小文字確認)

    大文字小文字かどうかを確認するメソッドもあります。

    text1 = "HELLO"
    text2 = "hello"
    text3 = "Hello"
    
    print(text1.isupper())  # True
    print(text2.islower())  # True
    print(text3.isupper())  # False
    print(text3.islower())  # False
    
    # 実践活用: パスワード強度チェック
    password = "MyPassword123"
    has_upper = any(c.isupper() for c in password)
    has_lower = any(c.islower() for c in password)
    print(f"大文字を含む: {has_upper}")  # True
    print(f"小文字を含む: {has_lower}")  # True

    🎯 学習目標 3: 検索/置換メソッドを習得する

    検索メソッド比較

    検索メソッドの特徴:

    • find(sub):見つかった場合は位置を返し(int)、見つからない場合は-1を返す(安全な検索)

    • index(sub):見つかった場合は位置を返し(int)、見つからない場合はValueErrorを発生(確実な時だけ使用)

    • count(sub):出現回数を返す(int)、見つからない場合は0を返す(頻度分析)

    • startswith(prefix):True/False、見つからない場合はFalse(接頭辞確認)

    • endswith(suffix):True/False、見つからない場合はFalse(接尾辞確認)

    find() - 安全な検索

    text = "Python is fun"
    
    # 基本使用
    print(text.find("is"))      # 7
    print(text.find("Java"))    # -1(見つからない)
    
    # 開始位置指定
    print(text.find("n"))       # 5(最初のn)
    print(text.find("n", 6))    # 13(6番位置以降のn)
    
    # 開始/終了範囲指定
    print(text.find("n", 0, 10))  # 5(0~10範囲で検索)
    
    # 実践活用: 文字列含有確認
    if text.find("Python") != -1:
        print("Pythonが含まれています")

    index() - エラー発生型検索

    text = "Python is fun"
    
    # 見つかった場合は位置を返す
    print(text.index("is"))  # 7
    
    # 見つからない場合はValueError
    try:
        print(text.index("Java"))  # ValueError発生!
    except ValueError:
        print("見つかりません")
    
    # 実践活用: 確実に存在する場合のみ使用
    email = "user@example.com"
    at_position = email.index("@")  # @記号は必ず存在
    domain = email[at_position + 1:]
    print(domain)  # example.com

    count() - 出現回数を数える

    text = "banana"
    print(text.count("a"))   # 3
    print(text.count("na"))  # 2
    print(text.count("x"))   # 0
    
    # 実践活用: 単語頻度分析
    article = "Python is great. Python is easy. Python is fun."
    python_count = article.count("Python")
    print(f"Pythonが{python_count}回出現します")  # 3回

    startswith() / endswith() - 開始/終了確認

    filename = "document.pdf"
    
    # 開始確認
    print(filename.startswith("doc"))  # True
    print(filename.startswith("img"))  # False
    
    # 終了確認
    print(filename.endswith(".pdf"))  # True
    print(filename.endswith(".txt"))  # False
    
    # 複数条件同時確認(タプル使用)
    image_file = "photo.jpg"
    is_image = image_file.endswith((".jpg", ".png", ".gif"))
    print(is_image)  # True
    
    # 実践活用: ファイルフィルタリング
    files = ["report.pdf", "image.png", "script.py", "data.csv"]
    python_files = [f for f in files if f.endswith(".py")]
    print(python_files)  # ['script.py']

    replace() - 文字列置換

    text = "Hello World"
    print(text.replace("World", "Python"))  # Hello Python
    
    # 回数指定
    text = "a b a c a"
    print(text.replace("a", "x"))      # x b x c x(すべて)
    print(text.replace("a", "x", 2))   # x b x c a(2回だけ)
    
    # 実践活用: データクレンジング
    raw_phone = "090-1234-5678"
    clean_phone = raw_phone.replace("-", "")
    print(clean_phone)  # 09012345678
    
    # 連鎖replace
    text = "Hello, World!"
    clean = text.replace(",", "").replace("!", "")
    print(clean)  # Hello World

    strip() / lstrip() / rstrip() - 空白削除

    text = "  hello  "
    
    # 両端の空白削除
    print(f"'{text.strip()}'")   # 'hello'
    
    # 左側だけ
    print(f"'{text.lstrip()}'")  # 'hello  '
    
    # 右側だけ
    print(f"'{text.rstrip()}'")  # '  hello'
    
    # 特定文字削除
    text = "xxxhelloxxx"
    print(text.strip("x"))  # hello
    
    text = "...hello..."
    print(text.strip("."))  # hello
    
    # 実践活用: ユーザー入力のクレンジング
    user_input = "  john@example.com  "
    clean_input = user_input.strip()
    print(clean_input)  # john@example.com

    🎯 学習目標 4: 分割/結合メソッドを習得する

    split() - 文字列をリストに分割

    基本構造:文字列.split(区切り文字, 最大分割回数)

    # 空白で分割(デフォルト)
    text = "apple banana grape"
    words = text.split()
    print(words)  # ['apple', 'banana', 'grape']
    
    # 特定の区切り文字で分割
    text = "2024-03-17"
    parts = text.split("-")
    print(parts)  # ['2024', '03', '17']
    
    # 分割回数制限
    text = "a:b:c:d"
    print(text.split(":"))     # ['a', 'b', 'c', 'd']
    print(text.split(":", 1))  # ['a', 'b:c:d'](1回だけ)
    print(text.split(":", 2))  # ['a', 'b', 'c:d'](2回だけ)

    split() 実践活用例

    CSV解析:

    csv_line = "山田太郎,25,東京,開発者"
    fields = csv_line.split(",")
    name, age, city, job = fields
    
    print(f"名前: {name}")  # 山田太郎
    print(f"年齢: {age}")   # 25
    print(f"都市: {city}")  # 東京
    print(f"職業: {job}")   # 開発者

    パス分割:

    path = "/home/user/documents/file.txt"
    parts = path.split("/")
    print(parts)  # ['', 'home', 'user', 'documents', 'file.txt']
    
    # ファイル名抽出
    filename = parts[-1]
    print(filename)  # file.txt

    タグ解析:

    tags = "python,javascript,java,c++"
    tag_list = tags.split(",")
    print(tag_list)  # ['python', 'javascript', 'java', 'c++']

    join() - リストを文字列に結合

    基本構造:「"区切り文字".join(リスト)」

    # 空白で結合
    words = ["apple", "banana", "grape"]
    text = " ".join(words)
    print(text)  # apple banana grape
    
    # 様々な区切り文字
    print("-".join(words))   # apple-banana-grape
    print(", ".join(words))  # apple, banana, grape
    print("\n".join(words))  # 改行で結合
    
    # 空文字列で結合
    letters = ["H", "e", "l", "l", "o"]
    word = "".join(letters)
    print(word)  # Hello

    join() 実践活用例

    パス結合:

    path_parts = ["home", "user", "documents", "file.txt"]
    path = "/".join(path_parts)
    print(path)  # home/user/documents/file.txt

    SQLクエリ生成:

    columns = ["id", "name", "age", "city"]
    sql = f"SELECT {', '.join(columns)} FROM users"
    print(sql)
    # SELECT id, name, age, city FROM users

    タグ生成:

    tags = ["python", "tutorial", "beginner"]
    hashtags = "#" + " #".join(tags)
    print(hashtags)  # #python #tutorial #beginner

    分割と結合の組み合わせ

    データ変換:

    # 日付形式変換: YYYY-MM-DD → YYYY/MM/DD
    date = "2024-03-17"
    parts = date.split("-")
    new_date = "/".join(parts)
    print(new_date)  # 2024/03/17

    大文字小文字変換と組み合わせ:

    sentence = "hello world python"
    words = sentence.split()
    capitalized = [word.capitalize() for word in words]
    result = " ".join(capitalized)
    print(result)  # Hello World Python

    その他の便利なメソッド

    center()、ljust()、rjust() - 整列

    text = "Python"
    
    # 中央揃え(合計20文字)
    print(text.center(20, "-"))  # -------Python-------
    
    # 左揃え
    print(text.ljust(20, "-"))   # Python--------------
    
    # 右揃え
    print(text.rjust(20, "-"))   # --------------Python

    zfill() - 数字の前に0を埋める

    # 数字を文字列に変換後0を埋める
    num = "42"
    print(num.zfill(5))  # 00042
    
    # ファイルナンバリング
    for i in range(1, 11):
        filename = f"file_{str(i).zfill(3)}.txt"
        print(filename)
    # file_001.txt
    # file_002.txt
    # ...
    # file_010.txt

    💡 実践のコツと注意点

    ポイント1:find()とindex()の選択

    text = "Python is fun"
    
    # ❌ 危険な方法(見つからないとエラー)
    pos = text.index("Java")  # ValueError発生!
    
    # ✅ 安全な方法
    pos = text.find("Java")
    if pos != -1:
        print(f"見つかった: {pos}")
    else:
        print("見つからない")
    
    # ✅ 確実に存在する場合のみindex()を使用
    email = "user@example.com"
    at_pos = email.index("@")  # @記号は必ず存在

    ポイント2:split()とmaxsplitの活用

    # maxsplitで分割回数制限
    url = "https://example.com/blog/2024/03/17"
    protocol, rest = url.split("://", 1)
    print(protocol)  # https
    print(rest)      # example.com/blog/2024/03/17
    
    # 空文字列に注意
    text = "a::b::c"
    print(text.split("::"))  # ['a', 'b', 'c']
    
    text = "::a::b::"
    print(text.split("::"))  # ['', 'a', 'b', ''](空文字列を含む)

    ポイント3:strip()は両端のみ削除

    # ❌ 中間の空白は削除されない
    text = "  hello  world  "
    print(text.strip())  # "hello  world"(中間の空白はそのまま)
    
    # ✅ すべての空白を削除するにはreplace()を使用
    text = "  hello  world  "
    clean = text.replace(" ", "")
    print(clean)  # "helloworld"
    
    # ✅ またはsplit()とjoin()の組み合わせ
    words = text.split()
    clean = " ".join(words)
    print(clean)  # "hello world"(空白1個に正規化)

    ポイント4:メソッドチェーン

    # 複数のメソッドを連結して使用
    text = "  HELLO WORLD  "
    result = text.strip().lower().replace(" ", "_")
    print(result)  # hello_world
    
    # 実践活用: URLスラッグ生成
    title = "  Python Tutorial: Day 17  "
    slug = title.strip().lower().replace(" ", "-").replace(":", "")
    print(slug)  # python-tutorial-day-17

    ポイント5:join()は文字列メソッド

    # ❌ リストメソッドではない
    words = ["a", "b", "c"]
    # result = words.join("-")  # AttributeError!
    
    # ✅ 区切り文字列のメソッド
    result = "-".join(words)
    print(result)  # a-b-c
    
    # join()は文字列のみ結合可能
    numbers = [1, 2, 3]
    # result = "-".join(numbers)  # TypeError!
    
    # ✅ 文字列に変換後結合
    result = "-".join(str(n) for n in numbers)
    print(result)  # 1-2-3

    ポイント6:判別メソッドの組み合わせ

    # パスワード強度チェック
    def check_password_strength(password):
        has_upper = any(c.isupper() for c in password)
        has_lower = any(c.islower() for c in password)
        has_digit = any(c.isdigit() for c in password)
        has_special = any(not c.isalnum() for c in password)
        is_long = len(password) >= 8
    
        if all([has_upper, has_lower, has_digit, has_special, is_long]):
            return "強い"
        elif sum([has_upper, has_lower, has_digit, has_special]) >= 3 and is_long:
            return "普通"
        else:
            return "弱い"
    
    print(check_password_strength("Pass123!"))  # 強い
    print(check_password_strength("password"))  # 弱い

    🧪 練習問題

    問題 1: ユーザー名検証システム

    課題: ユーザー名が有効かどうかを検証するプログラムを作成してください。複数の文字列メソッドを組み合わせて様々な条件を検査します。

    初期データ:

    usernames = [
        "tanaka123",      # 有効
        "Kim_456",        # 有効
        "  yamada789  ",  # 空白を含む
        "SATO!@#",        # 特殊文字を含む
        "ito",            # 短すぎる
        "suzuki_2024_ok", # 有効
        "1234numbers",    # 数字で始まる
        "VeryLongUsername1234567890"  # 長すぎる
    ]

    要件:

    1. ユーザー名の有効性条件:

      • 長さ: 5~15文字

      • 英数字のみ許可(アンダースコア 「_」 許可)

      • 数字で始まらない

      • 前後の空白は自動削除

      • 大文字小文字の区別なし(すべて小文字に変換)

    2. 各ユーザー名について以下の情報を出力:

      • 元の名前

      • 正規化された名前(前後の空白削除、小文字変換)

      • 有効性と具体的な理由

    3. 文字列メソッドの活用:

      • strip():前後の空白削除

      • lower():小文字変換

      • replace():特殊文字確認用

      • isalnum()、isdigit():文字タイプ判別

      • startswith():開始文字検査

    💡 ヒント

    • 前後の空白削除:「username.strip()」

    • 小文字変換:「username.lower()」

    • 長さ確認:「len(username)」

    • 最初の文字が数字か:「username[0].isdigit()」

    • アンダースコア許可: アンダースコアを空文字列に置換後「isalnum()」検査

    • 「for」ループで各文字を検査


    ✅ 解答

    usernames = [
        "tanaka123",      # 有効
        "Kim_456",        # 有効
        "  yamada789  ",  # 空白を含む
        "SATO!@#",        # 特殊文字を含む
        "ito",            # 短すぎる
        "suzuki_2024_ok", # 有効
        "1234numbers",    # 数字で始まる
        "VeryLongUsername1234567890"  # 長すぎる
    ]
    
    print("===== ユーザー名検証システム =====\n")
    
    for username in usernames:
        print(f"元の名前: '{username}'")
    
        # ステップ1: 正規化(前後の空白削除 + 小文字変換)
        normalized = username.strip().lower()
        print(f"正規化: '{normalized}'")
    
        # ステップ2: 有効性検査
        is_valid = True
        reason = "有効"
    
        # 長さ検査(5~15文字)
        if len(normalized) < 5:
            is_valid = False
            reason = "短すぎる(5文字以上必要)"
        elif len(normalized) > 15:
            is_valid = False
            reason = "長すぎる(15文字以下必要)"
    
        # 数字で始まるか検査
        elif normalized[0].isdigit():
            is_valid = False
            reason = "数字で始まることはできない"
    
        # 英数字、アンダースコアのみ許可
        else:
            for char in normalized:
                if not (char.isalnum() or char == "_"):
                    is_valid = False
                    reason = f"許可されていない文字を含む: '{char}'"
                    break
    
        # 結果出力
        status = "✅ 有効" if is_valid else "❌ 無効"
        print(f"結果: {status} - {reason}")
        print("-" * 50)
    
    # 追加テスト: 特定名前の詳細検証
    print("\n===== 詳細検証例 =====")
    test_name = "  Tanaka_123  "
    print(f"テスト名: '{test_name}'")
    
    # 段階的正規化
    step1 = test_name.strip()
    print(f"1. 空白削除: '{step1}'")
    
    step2 = step1.lower()
    print(f"2. 小文字変換: '{step2}'")
    
    # 文字分析
    print(f"\n文字分析:")
    print(f"  - 長さ: {len(step2)}文字")
    print(f"  - 最初の文字: '{step2[0]}' (数字: {step2[0].isdigit()})")
    print(f"  - 最後の文字: '{step2[-1]}'")
    
    # 各文字タイプ検査
    print(f"  - 文字別タイプ:")
    for i, char in enumerate(step2):
        char_type = []
        if char.isalpha():
            char_type.append("英字")
        if char.isdigit():
            char_type.append("数字")
        if char == "_":
            char_type.append("アンダースコア")
        if not char.isalnum() and char != "_":
            char_type.append("特殊文字")
        print(f"      {i}: '{char}' - {', '.join(char_type)}")

    出力:

    ===== ユーザー名検証システム =====
    
    元の名前: 'tanaka123'
    正規化: 'tanaka123'
    結果: ✅ 有効 - 有効
    --------------------------------------------------
    元の名前: 'Kim_456'
    正規化: 'kim_456'
    結果: ✅ 有効 - 有効
    --------------------------------------------------
    元の名前: '  yamada789  '
    正規化: 'yamada789'
    結果: ✅ 有効 - 有効
    --------------------------------------------------
    元の名前: 'SATO!@#'
    正規化: 'sato!@#'
    結果: ❌ 無効 - 許可されていない文字を含む: '!'
    --------------------------------------------------
    元の名前: 'ito'
    正規化: 'ito'
    結果: ❌ 無効 - 短すぎる(5文字以上必要)
    --------------------------------------------------
    元の名前: 'suzuki_2024_ok'
    正規化: 'suzuki_2024_ok'
    結果: ✅ 有効 - 有効
    --------------------------------------------------
    元の名前: '1234numbers'
    正規化: '1234numbers'
    結果: ❌ 無効 - 数字で始まることはできない
    --------------------------------------------------
    元の名前: 'VeryLongUsername1234567890'
    正規化: 'verylongusername1234567890'
    結果: ❌ 無効 - 長すぎる(15文字以下必要)
    --------------------------------------------------
    
    ===== 詳細検証例 =====
    テスト名: '  Tanaka_123  '
    1. 空白削除: 'Tanaka_123'
    2. 小文字変換: 'tanaka_123'
    
    文字分析:
      - 長さ: 10文字
      - 最初の文字: 't' (数字: False)
      - 最後の文字: '3'
      - 文字別タイプ:
          0: 't' - 英字
          1: 'a' - 英字
          2: 'n' - 英字
          3: 'a' - 英字
          4: 'k' - 英字
          5: 'a' - 英字
          6: '_' - アンダースコア
          7: '1' - 数字
          8: '2' - 数字
          9: '3' - 数字

    問題 2: テキストデータ分析・変換システム

    課題: 複数の文章からなるテキストを分析し、様々な方法で変換するプログラムを作成してください。

    初期データ:

    text = """
    Python is Easy. Python is Powerful. Python is Fun!
    Learn Python today. Start your Python journey now.
    """

    要件:

    1. テキスト基本分析:

      • 全文字数(空白含む/除く)

      • 単語数

      • 文数

      • 特定単語("Python")の出現回数(大文字小文字区別/非区別)

    2. テキスト変換:

      • すべての文の最初の文字を大文字に変換

      • 空白をアンダースコア(「_」)に変換

      • URLスラッグ形式に変換(小文字、ハイフン区切り)

      • 単語リストの抽出とソート

    3. 検索機能:

      • 特定単語の最初の位置

      • 特定単語で始まる文を探す

      • 特定単語で終わる文を探す

    💡 ヒント

    • 前後の空白削除: 「strip()」

    • 文の分離: 「split('.')」 または 「split('!')」

    • 単語の分離: 「split()」

    • 大文字小文字変換: 「upper()」, 「lower()」, 「title()」, 「capitalize()」

    • 特定文字数: 「count()」

    • 検索: 「find()」, 「index()」, 「startswith()」, 「endswith()」

    • 結合: 「join()」


    ✅ 解答

    text = """
    Python is Easy. Python is Powerful. Python is Fun!
    Learn Python today. Start your Python journey now.
    """
    
    print("===== テキストデータ分析 =====")
    print(f"元のテキスト:\n{text}\n")
    
    # ステップ1: テキスト正規化
    clean_text = text.strip()
    print(f"正規化されたテキスト:\n{clean_text}\n")
    
    # ステップ2: 基本分析
    print("===== 基本統計 =====")
    print(f"全文字数(空白含む): {len(clean_text)}文字")
    print(f"全文字数(空白除く): {len(clean_text.replace(' ', '').replace('\n', ''))}文字")
    
    # 単語数
    words = clean_text.split()
    print(f"単語数: {len(words)}個")
    
    # 文数(句点と感嘆符基準)
    sentences_dot = clean_text.split('.')
    sentences_excl = clean_text.split('!')
    sentence_count = len([s for s in sentences_dot if s.strip()]) + \
                     len([s for s in sentences_excl if s.strip() and '.' not in s]) - 1
    print(f"文数: {sentence_count}個")
    
    # Python単語の出現回数
    python_count = clean_text.count("Python")
    python_count_lower = clean_text.lower().count("python")
    print(f"'Python'の出現回数(大文字小文字区別): {python_count}回")
    print(f"'python'の出現回数(大文字小文字無視): {python_count_lower}回")
    
    # ステップ3: テキスト変換
    print("\n===== テキスト変換 =====")
    
    # すべての文の最初の文字を大文字
    title_text = clean_text.title()
    print(f"1. タイトルケース:\n{title_text}\n")
    
    # 空白をアンダースコアに
    underscore_text = clean_text.replace(" ", "_").replace("\n", "_")
    print(f"2. 空白 → アンダースコア:\n{underscore_text}\n")
    
    # URLスラッグ生成(1行に変換 + 小文字 + 特殊文字削除 + ハイフン)
    single_line = clean_text.replace("\n", " ")
    slug = single_line.strip().lower()
    for char in "!?,.":
        slug = slug.replace(char, " ")
    slug_words = slug.split()
    slug_final = "-".join(slug_words)
    print(f"3. URLスラッグ:\n{slug_final}\n")
    
    # ステップ4: 単語リストの抽出とソート
    print("===== 単語分析 =====")
    
    # 特殊文字を削除した単語リスト
    clean_words = []
    for word in words:
        # 特殊文字削除
        cleaned = word
        for char in "!?,.":
            cleaned = cleaned.replace(char, "")
        if cleaned:
            clean_words.append(cleaned.lower())
    
    # 重複削除とソート
    unique_words = list(set(clean_words))
    unique_words.sort()
    
    print(f"総単語数: {len(clean_words)}個")
    print(f"ユニーク単語数: {len(unique_words)}個")
    print(f"ユニーク単語リスト(ソート済み):\n{', '.join(unique_words)}")
    
    # ステップ5: 検索機能
    print("\n===== 検索機能 =====")
    
    # Pythonの最初の位置
    first_pos = clean_text.find("Python")
    print(f"'Python'の最初の位置: {first_pos}")
    
    # すべてのPython位置を探す
    print(f"'Python'のすべての位置:")
    start = 0
    positions = []
    while True:
        pos = clean_text.find("Python", start)
        if pos == -1:
            break
        positions.append(pos)
        start = pos + 1
    print(f"  位置: {positions}")
    
    # 文ごとの分析
    sentences = [s.strip() for s in clean_text.replace('!', '.').split('.') if s.strip()]
    print(f"\n文ごとの分析:")
    for i, sentence in enumerate(sentences, 1):
        print(f"  文 {i}: {sentence}")
        print(f"    - 'Python'で始まる: {sentence.startswith('Python')}")
        print(f"    - 'now'で終わる: {sentence.lower().endswith('now')}")
    
    # ステップ6: 単語出現頻度
    print("\n===== 単語出現頻度 TOP 5 =====")
    word_freq = {}
    for word in clean_words:
        word_freq[word] = word_freq.get(word, 0) + 1
    
    # 頻度順ソート
    sorted_freq = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)
    for i, (word, count) in enumerate(sorted_freq[:5], 1):
        print(f"{i}. '{word}': {count}回")

    出力:

    ===== テキストデータ分析 =====
    元のテキスト:
    
    Python is Easy. Python is Powerful. Python is Fun!
    Learn Python today. Start your Python journey now.
    
    
    正規化されたテキスト:
    Python is Easy. Python is Powerful. Python is Fun!
    Learn Python today. Start your Python journey now.
    
    ===== 基本統計 =====
    全文字数(空白含む): 103文字
    全文字数(空白除く): 84文字
    単語数: 15個
    文数: 5個
    'Python'の出現回数(大文字小文字区別): 5回
    'python'の出現回数(大文字小文字無視): 5回
    
    ===== テキスト変換 =====
    1. タイトルケース:
    Python Is Easy. Python Is Powerful. Python Is Fun!
    Learn Python Today. Start Your Python Journey Now.
    
    2. 空白 → アンダースコア:
    Python_is_Easy._Python_is_Powerful._Python_is_Fun!_Learn_Python_today._Start_your_Python_journey_now.
    
    3. URLスラッグ:
    python-is-easy-python-is-powerful-python-is-fun-learn-python-today-start-your-python-journey-now
    
    ===== 単語分析 =====
    総単語数: 15個
    ユニーク単語数: 11個
    ユニーク単語リスト(ソート済み):
    easy, fun, is, journey, learn, now, powerful, python, start, today, your
    
    ===== 検索機能 =====
    'Python'の最初の位置: 0
    'Python'のすべての位置:
      位置: [0, 16, 40, 63, 81]
    
    文ごとの分析:
      文 1: Python is Easy
        - 'Python'で始まる: True
        - 'now'で終わる: False
      文 2: Python is Powerful
        - 'Python'で始まる: True
        - 'now'で終わる: False
      文 3: Python is Fun
        - 'Python'で始まる: True
        - 'now'で終わる: False
      文 4: Learn Python today
        - 'Python'で始まる: False
        - 'now'で終わる: False
      文 5: Start your Python journey now
        - 'Python'で始まる: False
        - 'now'で終わる: True
    
    ===== 単語出現頻度 TOP 5 =====
    1. 'python': 5回
    2. 'is': 3回
    3. 'easy': 1回
    4. 'powerful': 1回
    5. 'fun': 1回

    🎯 練習問題の核心ポイント

    問題1で学んだこと:

    • メソッドチェーン:strip().lower()で複数の変換を連結

    • 判別メソッドの組み合わせ:isalnum()、isdigit()、isalpha()

    • 文字列の走査:「for char in string」で各文字を検査

    • 条件付き検証:様々な条件を段階的に検査

    • 正規化パターン:ユーザー入力処理の実践パターン

    問題2で学んだこと:

    • 複合テキスト分析:文字、単語、文レベルの多層分析

    • 検索メソッド:find()、startswith()、endswith()の活用

    • 変換メソッドの組み合わせ:split()、join()でデータ変換

    • 頻度分析:辞書と文字列メソッドの結合

    • 実践パターン:URLスラッグ、単語抽出、統計生成


    📝 今日学んだ内容のまとめ

    1. 文字列メソッド:文字列オブジェクトに内蔵された40個以上の便利な機能

    2. 大文字小文字変換:upper()、lower()、capitalize()、title()、swapcase()

    3. 検索メソッド:find()、index()、count()、startswith()、endswith()

    4. 変更メソッド:replace()、strip()、lstrip()、rstrip()

    5. 分割/結合:split()で分解、join()で組立

    6. 判別メソッド:isdigit()、isalpha()、isalnum()、isupper()、islower()


    🔗 関連資料


    📚 前回の学習

    Day 16: 文字列フォーマッティング(f-string) ⭐⭐

    前回は、f-stringで文字列をフォーマッティングする方法を学びました!

    📚 次回の学習

    Day 18: リスト内包表記を扱う(list-comprehension) ⭐⭐

    次回は、リストを簡潔に生成する内包表記の文法を学びます!

    📚 シリーズをまとめて読む

    Python 100日チャレンジの全記事は、
    マガジン「Python 100日チャレンジ」 でまとめて読めます 😊
    よろしければ、フォローしていただけると嬉しいです!


    🚀 遅いと思った時が一番早い時期です!🚀
    Day 17/100 | Phase 2: データ型をマスター | #100DaysOfPython

    よんよんわれ
     
     
    ソフトウェアエンジニアです。 ものづくりが好きで、プライベートでも複数のサイドプロジェクトに取り組んでいます。 最近は、AIと自動化を活用したサービス開発に力を入れています。 Note、Xなどでお友達になっていただけたら嬉しいです☺️

    あなたへのおすすめ