Pythonには、文字列を操作するための便利なメソッド(機能)がたくさん用意されています。
これらのメソッドをつかうことで、テキストの変換や検索、判定などを簡単に行うことができます。
この記事では、よくつかう文字列メソッドを目的別に整理して、初心者でもわかりやすく説明します。
文字列メソッドってなに?

説明
文字列メソッドとは、文字列に対して「○○をしなさい」という命令を出すための機能です。
例えば、「すべて大文字にしなさい」「特定の文字をさがしなさい」といった操作ができます。
基本的な使い方
文字列.メソッド名()
例:
"hello".upper() # 文字列"hello"に対して「大文字にしなさい」という命令
文字列の変換・整形
大文字・小文字の変換
説明
英語の文字列を大文字や小文字に変換したり、最初の文字だけを大文字にしたりできます。
メソッド一覧
メソッド | 説明 | 例 |
---|---|---|
upper() | すべて大文字にする | "hello".upper() → 'HELLO' |
lower() | すべて小文字にする | "HELLO".lower() → 'hello' |
capitalize() | 最初の文字だけ大文字、あとは小文字 | "hello world".capitalize() → 'Hello world' |
title() | 各単語の最初を大文字にする | "hello world".title() → 'Hello World' |
swapcase() | 大文字と小文字を反転する | "Hello World".swapcase() → 'hELLO wORLD' |
実際の例
# 名前を正しい形に整える
name = "tanaka taro"
print(name.title()) # Tanaka Taro
# ユーザー入力を統一する
user_input = "YES"
print(user_input.lower()) # yes
# メールアドレスを小文字に統一
email = "User@Example.COM"
print(email.lower()) # user@example.com
文字列の位置揃え
説明
文字列を指定した幅の中で、左寄せ・右寄せ・中央寄せすることができます。
メソッド一覧
メソッド | 説明 | 例 |
---|---|---|
center(幅, 埋める文字) | 中央寄せ | "hello".center(10, '-') → '--hello---' |
ljust(幅, 埋める文字) | 左寄せ | "hello".ljust(10, '-') → 'hello-----' |
rjust(幅, 埋める文字) | 右寄せ | "hello".rjust(10, '-') → '-----hello' |
zfill(幅) | 左側を0で埋める | "42".zfill(5) → '00042' |
実際の例
# 表を作るときの整列
print("名前".center(10, ' ')) # " 名前 "
print("年齢".center(10, ' ')) # " 年齢 "
# 番号をゼロ埋めする
number = "123"
print(number.zfill(6)) # 000123
# ファイル名を作る
file_id = "5"
filename = f"file_{file_id.zfill(3)}.txt" # file_005.txt
文字列の検索・判定
文字列をさがす
説明
文字列の中に特定の文字や単語が含まれているかをさがしたり、その位置を調べたりできます。
メソッド一覧
メソッド | 説明 | 戻り値 |
---|---|---|
find(文字列) | 文字列の位置をさがす | 見つかった位置(数字)、見つからない場合は-1 |
index(文字列) | 文字列の位置をさがす | 見つかった位置(数字)、見つからない場合はエラー |
count(文字列) | 文字列の出現回数を数える | 回数(数字) |
in 演算子 | 文字列が含まれているか | True または False |
実際の例
text = "hello world hello"
# 文字列をさがす
print(text.find("world")) # 6(6番目の位置にある)
print(text.find("python")) # -1(見つからない)
# 出現回数を数える
print(text.count("hello")) # 2(2回出現)
print(text.count("l")) # 4(lが4回出現)
# 含まれているかチェック
print("world" in text) # True
print("python" in text) # False
# メールアドレスの簡単チェック
email = "user@example.com"
if "@" in email and "." in email:
print("メールアドレスの形式です")
文字列の始まりと終わりをチェック
説明
文字列が特定の文字で始まっているか、終わっているかを調べることができます。
メソッド一覧
メソッド | 説明 | 例 |
---|---|---|
startswith(文字列) | 指定した文字で始まるか | "hello".startswith("he") → True |
endswith(文字列) | 指定した文字で終わるか | "hello".endswith("lo") → True |
実際の例
filename = "document.pdf"
# ファイルの種類をチェック
if filename.endswith(".pdf"):
print("PDFファイルです")
elif filename.endswith(".txt"):
print("テキストファイルです")
# URLのチェック
url = "https://example.com"
if url.startswith("https://"):
print("安全なHTTPS接続です")
elif url.startswith("http://"):
print("HTTP接続です")
# 電話番号のチェック
phone = "090-1234-5678"
if phone.startswith("090") or phone.startswith("080"):
print("携帯電話番号です")
文字列の分割・結合

文字列を分割する
説明
文字列を指定した区切り文字で分割して、リスト(複数の要素を持つデータ)に変換できます。
メソッド
メソッド | 説明 | 例 |
---|---|---|
split(区切り文字) | 指定した文字で分割 | "a,b,c".split(",") → ['a', 'b', 'c'] |
splitlines() | 改行で分割 | "行1\n行2".splitlines() → ['行1', '行2'] |
実際の例
# CSVデータの処理
data = "apple,banana,cherry,grape"
fruits = data.split(",")
print(fruits) # ['apple', 'banana', 'cherry', 'grape']
# 名前の分割
full_name = "田中 太郎"
name_parts = full_name.split(" ")
last_name = name_parts[0] # 田中
first_name = name_parts[1] # 太郎
# パスの分割
file_path = "/home/user/documents/file.txt"
path_parts = file_path.split("/")
print(path_parts) # ['', 'home', 'user', 'documents', 'file.txt']
# 複数行テキストの処理
text = """行1
行2
行3"""
lines = text.splitlines()
print(lines) # ['行1', '行2', '行3']
文字列を結合する
説明
リストの要素を指定した文字で結合して、1つの文字列にできます。
メソッド
メソッド | 説明 | 例 |
---|---|---|
"区切り文字".join(リスト) | リストを結合 | ",".join(['a', 'b', 'c']) → 'a,b,c' |
実際の例
# リストをCSV形式にする
fruits = ['apple', 'banana', 'cherry']
csv_data = ",".join(fruits)
print(csv_data) # apple,banana,cherry
# パスを作成する
path_parts = ['home', 'user', 'documents', 'file.txt']
file_path = "/".join(path_parts)
print(file_path) # home/user/documents/file.txt
# 名前を結合する
last_name = "田中"
first_name = "太郎"
full_name = " ".join([last_name, first_name])
print(full_name) # 田中 太郎
# HTMLタグを作成する
items = ['項目1', '項目2', '項目3']
html_list = "</li><li>".join(items)
html = f"<li>{html_list}</li>"
print(html) # <li>項目1</li><li>項目2</li><li>項目3</li>
文字列の削除・置換
不要な文字を削除する
説明
文字列の前後にある空白や、指定した文字を削除できます。
メソッド一覧
メソッド | 説明 | 例 |
---|---|---|
strip() | 前後の空白を削除 | " hello ".strip() → 'hello' |
strip(文字) | 前後の指定文字を削除 | "...hello...".strip(".") → 'hello' |
lstrip() | 左側の空白を削除 | " hello".lstrip() → 'hello' |
rstrip() | 右側の空白を削除 | "hello ".rstrip() → 'hello' |
実際の例
# ユーザー入力の整理
user_input = " 田中太郎 "
clean_name = user_input.strip()
print(f"'{clean_name}'") # '田中太郎'
# ファイルの各行を整理
lines = [" 行1 \n", " 行2 \n", " 行3 \n"]
clean_lines = [line.strip() for line in lines]
print(clean_lines) # ['行1', '行2', '行3']
# 特定の文字を削除
code = "###ABCD###"
clean_code = code.strip("#")
print(clean_code) # ABCD
文字列を置き換える
説明
文字列の中の特定の部分を別の文字列に置き換えることができます。
メソッド
メソッド | 説明 | 例 |
---|---|---|
replace(古い文字, 新しい文字) | すべて置換 | "banana".replace("a", "o") → 'bonono' |
replace(古い文字, 新しい文字, 回数) | 指定回数だけ置換 | "banana".replace("a", "o", 2) → 'bonona' |
実際の例
# テキストの修正
text = "これは古いバージョンです。古い機能をつかっています。"
new_text = text.replace("古い", "新しい")
print(new_text) # これは新しいバージョンです。新しい機能をつかっています。
# ファイルパスの修正
windows_path = "C:\\Users\\Name\\Documents"
unix_path = windows_path.replace("\\", "/")
print(unix_path) # C:/Users/Name/Documents
# 電話番号の整形
phone = "090-1234-5678"
phone_clean = phone.replace("-", "")
print(phone_clean) # 09012345678
# 一部だけ置換
text = "aaa bbb aaa ccc aaa"
result = text.replace("aaa", "xxx", 2) # 最初の2個だけ置換
print(result) # xxx bbb xxx ccc aaa
文字列の性質判定

文字の種類をチェックする
説明
文字列がどんな種類の文字で構成されているかを調べることができます。
メソッド一覧
メソッド | 説明 | 例 |
---|---|---|
isalpha() | すべてアルファベット | "Hello".isalpha() → True |
isdigit() | すべて数字 | "123".isdigit() → True |
isalnum() | アルファベットまたは数字 | "abc123".isalnum() → True |
isspace() | すべて空白文字 | " ".isspace() → True |
isupper() | すべて大文字 | "HELLO".isupper() → True |
islower() | すべて小文字 | "hello".islower() → True |
実際の例
# ユーザー入力の検証
user_id = input("ユーザーIDを入力してください: ")
if user_id.isalnum():
print("有効なユーザーIDです")
else:
print("ユーザーIDは英数字のみにしてください")
# 年齢の検証
age_input = input("年齢を入力してください: ")
if age_input.isdigit():
age = int(age_input)
print(f"年齢: {age}歳")
else:
print("数字を入力してください")
# パスワードの強度チェック
password = input("パスワードを入力してください: ")
if len(password) >= 8:
if any(c.isupper() for c in password):
if any(c.islower() for c in password):
if any(c.isdigit() for c in password):
print("強いパスワードです")
else:
print("数字も含めてください")
else:
print("小文字も含めてください")
else:
print("大文字も含めてください")
else:
print("8文字以上にしてください")
文字列のフォーマット
文字列に値を埋め込む
説明
文字列の中に変数の値を埋め込んで、動的な文字列を作ることができます。
方法一覧
方法 | 説明 | 例 |
---|---|---|
f-string | 最も新しく推奨される方法 | f"Hello, {name}!" |
format() | 従来の方法 | "Hello, {}!".format(name) |
% 形式 | 古い方法 | "Hello, %s!" % name |
実際の例
name = "田中さん"
age = 25
score = 85.5
# f-string(推奨)
message1 = f"こんにちは、{name}。あなたは{age}歳で、スコアは{score}です。"
print(message1)
# format()メソッド
message2 = "こんにちは、{}。あなたは{}歳で、スコアは{}です。".format(name, age, score)
print(message2)
# 名前付きフォーマット
message3 = "こんにちは、{name}。あなたは{age}歳です。".format(name=name, age=age)
print(message3)
# 数値のフォーマット
price = 1234.56
print(f"価格: ¥{price:,.2f}") # 価格: ¥1,234.56
# 日付のフォーマット
from datetime import datetime
now = datetime.now()
print(f"現在時刻: {now:%Y年%m月%d日 %H時%M分}")
その他の便利なメソッド
エンコーディング
説明
文字列をバイト列に変換したり、バイト列を文字列に戻したりできます。
メソッド
メソッド | 説明 | 例 |
---|---|---|
encode(エンコーディング) | 文字列をバイト列に変換 | "hello".encode("utf-8") |
decode(エンコーディング) | バイト列を文字列に変換 | b"hello".decode("utf-8") |
実際の例
# 日本語のエンコード
japanese = "こんにちは"
encoded = japanese.encode("utf-8")
print(encoded) # b'\xe3\x81\x93\xe3\x82\x93\xe3\x81\xab\xe3\x81\xa1\xe3\x81\xaf'
# デコード
decoded = encoded.decode("utf-8")
print(decoded) # こんにちは
# ファイル保存時のエンコード指定
text = "保存するテキスト"
with open("file.txt", "w", encoding="utf-8") as f:
f.write(text)
よくある使用例
データ処理の実例
# CSVファイルのような文字列を処理
csv_data = """name,age,city
田中,25,東京
佐藤,30,大阪
山田,28,名古屋"""
lines = csv_data.strip().splitlines()
header = lines[0].split(",")
for line in lines[1:]:
values = line.split(",")
person = dict(zip(header, values))
print(f"{person['name']}さん({person['age']}歳)は{person['city']}在住")
# ログファイルの解析
log_entry = "2025-06-05 14:30:15 ERROR: ファイルが見つかりません"
if "ERROR" in log_entry:
parts = log_entry.split(" ", 2) # 最大2回分割
timestamp = parts[0] + " " + parts[1]
message = parts[2]
print(f"エラー発生時刻: {timestamp}")
print(f"エラー内容: {message}")
テキスト整形の実例
# マークダウン風のテキスト処理
text = """
# タイトル
これは本文です。
## サブタイトル
ここも本文です。
"""
lines = text.strip().splitlines()
formatted_lines = []
for line in lines:
line = line.strip()
if line.startswith("# "):
formatted_lines.append(f"【{line[2:]}】")
elif line.startswith("## "):
formatted_lines.append(f"◆{line[3:]}")
elif line:
formatted_lines.append(f" {line}")
result = "\n".join(formatted_lines)
print(result)
まとめ
Pythonの文字列メソッドのポイント
- 変換・整形:
upper()
,lower()
,strip()
,center()
- 検索・判定:
find()
,count()
,startswith()
,endswith()
- 分割・結合:
split()
,join()
- 削除・置換:
strip()
,replace()
- 性質判定:
isalpha()
,isdigit()
,isspace()
- フォーマット:f-string,
format()
コメント