Python | 文字列メソッド

Python
スポンサーリンク

文字列メソッドの基本とよく使う操作

初めてでも使えるように、言葉をやさしく、動く例をたくさん入れて説明します。まずは「文字列メソッドって何?」から始めましょう。


文字列メソッドとは何か

  • メソッドの意味:
    「データにくっついている専用の道具(関数)」のこと。文字列にくっついている道具は、文字の変換や検索に使う。
  • 書き方の形:
    文字列.メソッド名(必要なら引数) の形で使う。例えば name.upper() のように書く。
  • 関数との違い:
    • 関数: len("hello") のように、データをカッコの中に渡す。
    • メソッド: "hello".upper() のように、データの後ろに「.」で呼び出す。
  • 重要ポイント(変更されない):
    文字列は「不変(immutable)」。メソッドは基本的に「新しい文字列」を返し、元の文字列は変わらない。
text = "Hello"
text.upper()      # "HELLO" を返す
print(text)       # まだ "Hello" のまま
text = text.upper()  # 代入すれば更新できる
print(text)          # "HELLO"
Python

大文字・小文字の変換

  • upper():すべて大文字に
    例)ユーザー名を表示用に揃える
username = "yuko"
print(username.upper())  # "YUKO"
Python
  • lower():すべて小文字に
    例)検索時に大小文字を気にしない比較
keyword = "Python"
user_input = "PYTHON"
print(keyword.lower() == user_input.lower())  # True
Python
  • capitalize():先頭だけ大文字、他は小文字
title = "hELLO wORLD"
print(title.capitalize())  # "Hello world"
Python
  • title():単語ごとに先頭を大文字
book = "the lord of the rings"
print(book.title())  # "The Lord Of The Rings"
Python

前後の空白や改行を消す

  • strip():両端の空白・改行を削る
    入力処理でほぼ必須
raw = "  hello\n"
print(raw.strip())  # "hello"
Python
  • lstrip() / rstrip():左側だけ/右側だけ
text = "  padded  "
print(text.lstrip())  # "padded  "
print(text.rstrip())  # "  padded"
Python
  • 特定文字を削る(引数で指定)
url = "////path////"
print(url.strip("/"))  # "path"
Python

部分一致のチェックと検索

  • startswith() / endswith():始まり・終わりの判定
filename = "report.csv"
print(filename.endswith(".csv"))    # True
print(filename.startswith("report"))# True
Python
  • find():位置を見つける(なければ -1)
word = "banana"
print(word.find("na"))  # 2(最初に見つかった位置)
print(word.find("xy"))  # -1
Python
  • index():位置を見つける(なければエラー)
word = "banana"
print(word.index("na"))     # 2
# word.index("xy")          # ValueError(見つからないとエラー)
Python
  • count():出現回数を数える
text = "abracadabra"
print(text.count("abra"))  # 2
Python

置換と分割・結合

  • replace(old, new):置き換え
    例)入力ミスの一括修正
msg = "I like Java"
print(msg.replace("Java", "Python"))  # "I like Python"
Python
  • split(sep):区切ってリストに
    CSV・ログ解析の基本
line = "apple,banana,grape"
parts = line.split(",")
print(parts)  # ["apple", "banana", "grape"]
Python
  • split()(引数なし):連続空白で分割
s = "  multiple   spaces here "
print(s.split())  # ["multiple", "spaces", "here"]
Python
  • join(list):リストをつないで文字列に
    「joinは文字列側に書く」ことに注意
items = ["2021", "11", "06"]
print("-".join(items))  # "2021-11-06"
Python

文字の種類チェック(バリデーション)

  • isdigit():数字だけ
age = "25"
print(age.isdigit())  # True
Python
  • isalpha():英字だけ
name = "Yuko"
print(name.isalpha())  # True
Python
  • isalnum():英数字だけ
code = "AB12"
print(code.isalnum())  # True
Python
  • isspace():空白だけ
blank = "   \n"
print(blank.isspace())  # True
Python
  • 注意:"-12".isdigit() は False(マイナスや小数点を含むと数字だけではない)。数値判定は例外処理の方が安全な場合あり。
s = "-12.5"
try:
    val = float(s)
    print("数値です:", val)
except ValueError:
    print("数値ではありません")
Python

文字寄せ・ゼロ埋め・幅合わせ

  • zfill(width):左側をゼロで埋める
num = "42"
print(num.zfill(5))  # "00042"
Python
  • rjust(width) / ljust(width):右寄せ/左寄せ
item = "apple"
print(item.rjust(10))  # "     apple"
print(item.ljust(10))  # "apple     "
Python
  • center(width):中央寄せ
title = "Menu"
print(title.center(10, "-"))  # "---Menu---"
Python

実践ミニ問題(動かして慣れる)

問題 1:入力をきれいにして判定

  • 目的: 前後の空白を取り、”yes” なら True、それ以外は False
ans = input("続けますか? (yes/no): ")
clean = ans.strip().lower()
print(clean == "yes")
Python

問題 2:CSVの価格合計を出す

  • 入力: “120, 300, 80” のような文字列
  • 出力: 合計 500
line = "120, 300, 80"
nums = [int(x.strip()) for x in line.split(",")]
print(sum(nums))  # 500
Python

問題 3:メールのドメインを取り出す

email = "user@example.com"
at = email.find("@")
domain = email[at+1:] if at != -1 else ""
print(domain)  # "example.com"
Python

問題 4:見出しの整形

  • 入力: ” hello WORLD “
  • 出力: “Hello world”
title = "  hello WORLD  "
formatted = title.strip().capitalize()
print(formatted)
Python

問題 5:禁則語を伏字にする

text = "This is a secret code."
bad = "secret"
masked = text.replace(bad, "*" * len(bad))
print(masked)  # "This is a ****** code."
Python

つまずきやすいポイントとコツ

  • 元の文字列は変わらない:
    変換後を使いたいときは「代入」する。
s = "abc"
s.upper()
print(s)       # "abc"
s = s.upper()  # これで更新
Python
  • join の主語は「区切り文字」:
    リストには join はない。",".join(list) の形を覚える。
  • findindex の違い:
    失敗時に find は -1、index はエラー。安全に書くなら find
  • 空白の扱い:
    入力の前後に予想外の空白・改行がつくことはよくある。strip() を習慣に。
  • 数字判定は例外処理が堅牢:
    isdigit() はマイナス・小数・全角数字に注意。float()try/except が実用的。

練習用の課題

  1. 電話番号の正規化:
    • 入力例:” 03- 1234-5678 “
    • 前後の空白を削る、連続空白や余計なスペースを消す、"-" の前後の空白も除去して “03-1234-5678” に整える。
  2. 拡張子チェックツール:
    • ファイル名を受け取り、.png または .jpg で終わるかを表示。
    • 大文字/小文字を気にしないよう lower() を使う。
  3. 単語カウント:
    • 文を入力し、split() で単語に分けて、len() で単語数を出す。
    • ついでに特定単語の出現回数を count() で数える。
  4. パスの前後スラッシュ整理:
    • 文字列の先頭末尾の /strip("/") で除去し、フォルダ名同士を " / ".join(...) でつないで表示する。

まとめの指針

  • 基礎の型: strip(整える)、lower/upper(揃える)、replace(直す)、split/join(分解と再構成)、find/count(探す・数える)。
  • 覚え方: 「入力は strip、比較は lower、連結は join、探すなら find」。このセットをまず手に馴染ませる。
  • 上達のコツ: いつも「代入が必要か?」を意識する(文字列は不変)。小さなスクリプトを作って、すぐ動かして手応えを得る。
Python
スポンサーリンク
シェアする
@lifehackerをフォローする
スポンサーリンク
タイトルとURLをコピーしました