ここでは「Python の文字列メソッド(str 型の関数)を、用途別に分類し、初心者でも読めるように例つきで整理」します。
単なる一覧ではなく、「どんなときに使うのか」もわかるように説明しています。
1. 大文字・小文字の変換系
| メソッド | 説明 | 使用例 |
|---|---|---|
.lower() | すべて小文字にする | "HELLO".lower() → "hello" |
.upper() | すべて大文字にする | "Hello".upper() → "HELLO" |
.capitalize() | 先頭だけ大文字にする | "python".capitalize() → "Python" |
.title() | 各単語の頭文字を大文字に | "hello world".title() → "Hello World" |
.swapcase() | 大文字↔小文字を反転 | "PyThOn".swapcase() → "pYtHoN" |
用途例:ユーザー入力を比較する前にすべて小文字にそろえるなど。
user = input("続けますか?(yes/no): ").lower()
if user == "yes":
print("続行します。")
Python2. 空白や改行の除去(トリミング)
| メソッド | 説明 | 使用例 |
|---|---|---|
.strip() | 前後の空白・改行を削除 | " hello ".strip() → "hello" |
.lstrip() | 左側のみ削除 | " hello".lstrip() → "hello" |
.rstrip() | 右側のみ削除 | "hello ".rstrip() → "hello" |
用途例:CSV やユーザー入力で、余分な空白を取りたいとき。
name = input("名前を入力: ").strip()
Python3. 文字列の分割・結合
| メソッド | 説明 | 使用例 |
|---|---|---|
.split(sep) | 区切り文字で分割(リストに) | "a,b,c".split(",") → ['a','b','c'] |
.rsplit(sep, n) | 右から n 回だけ分割 | "a,b,c".rsplit(",", 1) → ['a,b','c'] |
.splitlines() | 改行ごとに分割 | "A\nB\nC".splitlines() → ['A','B','C'] |
sep.join(list) | リストを区切り文字で結合 | ",".join(['A','B']) → "A,B" |
用途例:CSV、ログ、テキストファイルの分解や再構成。
names = "Alice,Bob,Charlie".split(",")
print(names) # ['Alice', 'Bob', 'Charlie']
print(" & ".join(names)) # "Alice & Bob & Charlie"
Python4. 検索・判定系
| メソッド | 説明 | 使用例 |
|---|---|---|
.find(sub) | 最初の位置を返す(なければ -1) | "banana".find("na") → 2 |
.rfind(sub) | 右から検索 | "banana".rfind("na") → 4 |
.index(sub) | 見つからないとエラー | "banana".index("na") → 2 |
.count(sub) | 出現回数を数える | "banana".count("na") → 2 |
.startswith(prefix) | 先頭が一致するか | "Python".startswith("Py") → True |
.endswith(suffix) | 末尾が一致するか | "file.txt".endswith(".txt") → True |
用途例:ファイル拡張子のチェック、検索、フィルタリングなど。
files = ["main.py", "readme.txt", "data.csv"]
py_files = [f for f in files if f.endswith(".py")]
print(py_files) # ['main.py']
Python5. 置換・加工系
| メソッド | 説明 | 使用例 |
|---|---|---|
.replace(old, new, count=None) | 部分文字列を置き換える | "apple".replace("p","P") → "aPPle" |
.translate(table) + str.maketrans() | 複数置換 | "abc".translate(str.maketrans("abc","123")) → "123" |
用途例:禁止文字を削除したり、記号を変換したり。
text = "Python3.10"
new_text = text.replace(".", "_")
print(new_text) # Python3_10
Python6. 文字の種類チェック(ブール値を返す)
| メソッド | 説明 | 使用例 |
|---|---|---|
.isalpha() | 英字のみ? | "Hello".isalpha() → True |
.isdigit() | 数字のみ? | "123".isdigit() → True |
.isalnum() | 英数字のみ? | "abc123".isalnum() → True |
.isspace() | 空白(スペース・改行)だけ? | " ".isspace() → True |
.islower() | すべて小文字? | "abc".islower() → True |
.isupper() | すべて大文字? | "ABC".isupper() → True |
.istitle() | 各単語の先頭が大文字? | "Hello World".istitle() → True |
用途例:入力チェック、データバリデーション。
code = input("数字を入力してください: ")
if not code.isdigit():
print("数字のみ入力してください!")
Python7. 配置・整形(出力整える)
| メソッド | 説明 | 使用例 |
|---|---|---|
.center(width, fillchar=' ') | 中央寄せ | "Hi".center(6, '-') → "--Hi--" |
.ljust(width, fillchar=' ') | 左寄せ | "Hi".ljust(6, '.') → "Hi...." |
.rjust(width, fillchar=' ') | 右寄せ | "Hi".rjust(6, '.') → "....Hi" |
.zfill(width) | 0で左埋め | "42".zfill(5) → "00042" |
用途例:レシートや表形式の整形出力など。
for i in range(1, 4):
print(str(i).zfill(3), ":", "Item", i)
# 001 : Item 1
# 002 : Item 2
# 003 : Item 3
Python8. 文字列を評価・変換(応用)
| メソッド | 説明 | 使用例 |
|---|---|---|
.encode(encoding) | バイト列に変換 | "日本語".encode("utf-8") |
.format() | 文字列フォーマット | "{}さんは{}歳".format("田中", 25) |
.format_map(dict) | 辞書を使ってフォーマット | "{name}は{age}歳".format_map({'name':'花子','age':20}) |
用途例:テンプレート文字列、メール文面、自動レポート生成。
data = {"name":"佐藤", "age":30}
msg = "{name}さんは{age}歳です".format_map(data)
print(msg)
Python9. その他(便利ツール)
| メソッド | 説明 | 使用例 |
|---|---|---|
.partition(sep) | 区切りで3分割(左・区切り・右) | "key=value".partition("=") → ('key', '=', 'value') |
.rpartition(sep) | 右から3分割 | "a=b=c".rpartition("=") → ('a=b', '=', 'c') |
.expandtabs(tabsize) | タブをスペースに展開 | "A\tB".expandtabs(4) → "A B" |
用途例:設定ファイルの解析や軽いパーサーに便利。
練習問題(メソッド総復習)
Q1. " Python " の前後の空白を取り除いて大文字に変換。
→
print(" Python ".strip().upper()) # "PYTHON"
PythonQ2. "A,B,C" を split() で分割し、join() で "A-B-C" に変換。
→
print("-".join("A,B,C".split(",")))
PythonQ3. "apple banana apple" の "apple" を "orange" に置換し、count("apple") の結果を出力。
→
s = "apple banana apple"
print(s.replace("apple", "orange"), s.count("apple"))
# orange banana orange 2
PythonQ4. "Python" が "Py" で始まり "on" で終わるか判定。
→
print("Python".startswith("Py"), "Python".endswith("on"))
Pythonまとめ
| 用途 | よく使うメソッド |
|---|---|
| 大文字小文字変換 | lower(), upper(), capitalize() |
| 空白除去 | strip(), lstrip(), rstrip() |
| 分割・結合 | split(), join(), splitlines() |
| 検索 | find(), count(), startswith() |
| 置換 | replace(), translate() |
| 判定 | isalpha(), isdigit(), isspace() |
| 整形 | center(), rjust(), zfill() |
