Python | Python 文字列メソッド リファレンス(用途別+例つき)

Python Python
スポンサーリンク

ここでは「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("続行します。")
Python

2. 空白や改行の除去(トリミング)

メソッド説明使用例
.strip()前後の空白・改行を削除" hello ".strip() → "hello"
.lstrip()左側のみ削除" hello".lstrip() → "hello"
.rstrip()右側のみ削除"hello ".rstrip() → "hello"

用途例:CSV やユーザー入力で、余分な空白を取りたいとき。

name = input("名前を入力: ").strip()
Python

3. 文字列の分割・結合

メソッド説明使用例
.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"
Python

4. 検索・判定系

メソッド説明使用例
.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']
Python

5. 置換・加工系

メソッド説明使用例
.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
Python

6. 文字の種類チェック(ブール値を返す)

メソッド説明使用例
.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("数字のみ入力してください!")
Python

7. 配置・整形(出力整える)

メソッド説明使用例
.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
Python

8. 文字列を評価・変換(応用)

メソッド説明使用例
.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)
Python

9. その他(便利ツール)

メソッド説明使用例
.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"
Python

Q2. "A,B,C" を split() で分割し、join() で "A-B-C" に変換。
→

print("-".join("A,B,C".split(",")))
Python

Q3. "apple banana apple" の "apple" を "orange" に置換し、count("apple") の結果を出力。
→

s = "apple banana apple"
print(s.replace("apple", "orange"), s.count("apple"))
# orange banana orange  2
Python

Q4. "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()
タイトルとURLをコピーしました