【保存版】Pythonの文字列メソッド一覧まとめ|使い方と活用例をわかりやすく解説

python

プログラミングをしていると、文字列をあつかう場面がとても多いです。
名前や住所、メールアドレス、ファイル名など、さまざまなデータが文字列として登場します。

「文字列のなかから特定の文字をさがしたい」
「大文字を小文字に変えたい」
「スペースをとりのぞきたい」

こんなとき、Pythonには文字列メソッドという便利な機能があります。

メソッドとは、データにたいして実行できる処理のことです。

この記事では、よく使う文字列メソッドを実例とともにわかりやすく紹介します。


スポンサーリンク

文字列の長さをしらべる・型を変える

len()関数で文字数をかぞえる

# 基本的な使い方
text = "こんにちは"
print(len(text))  # 結果: 5

# 実用例:パスワードの長さチェック
password = "abc123"
if len(password) < 8:
    print("パスワードは8文字以上にしてください")

ポイント: len()は関数なので、文字列を()のなかに入れます。

str()関数で文字列に変換する

# 数値を文字列に変える
number = 123
text = str(number)
print(text)  # 結果: "123"

# 実用例:数値と文字列をつなげる
age = 25
message = "私は" + str(age) + "歳です"
print(message)  # 結果: 私は25歳です

よくある間違い: 数値と文字列を直接つなげようとするとエラーになります。必ずstr()で変換しましょう。


大文字・小文字を変換する

lower()で小文字に変換

# 基本的な使い方
text = "HELLO"
result = text.lower()
print(result)  # 結果: hello

# 実用例:大文字小文字を区別しない比較
user_input = "YES"
if user_input.lower() == "yes":
    print("はいが選択されました")

upper()で大文字に変換

# 基本的な使い方
text = "hello"
result = text.upper()
print(result)  # 結果: HELLO

# 実用例:見出しを目立たせる
title = "重要なお知らせ"
print(title.upper())  # 結果: 重要なお知らせ

capitalize()で最初だけ大文字に

# 基本的な使い方
text = "python programming"
result = text.capitalize()
print(result)  # 結果: Python programming

# 実用例:名前の最初を大文字にする
name = "tanaka"
formatted_name = name.capitalize()
print(formatted_name)  # 結果: Tanaka

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

# 基本的な使い方
text = "hello world"
result = text.title()
print(result)  # 結果: Hello World

# 実用例:タイトルを整える
book_title = "python for beginners"
print(book_title.title())  # 結果: Python For Beginners

覚え方のコツ:

  • lower() = 低い → 小文字
  • upper() = 上 → 大文字
  • capitalize() = 最初の文字だけ
  • title() = タイトルみたいに各単語の最初

文字列をさがす・確認する

find()で文字の位置をさがす

# 基本的な使い方
text = "apple"
position = text.find("p")
print(position)  # 結果: 1 (0から数えて1番目)

# 実用例:メールアドレスの@マークをさがす
email = "user@example.com"
at_position = email.find("@")
if at_position != -1:  # -1は見つからなかった場合
    print("正しいメールアドレスの形式です")

startswith()で始まりの文字を確認

# 基本的な使い方
text = "Hello World"
result = text.startswith("Hello")
print(result)  # 結果: True

# 実用例:ファイル名の拡張子チェック
filename = "document.pdf"
if filename.lower().endswith(".pdf"):
    print("PDFファイルです")

endswith()で終わりの文字を確認

# 基本的な使い方
text = "python_file.py"
result = text.endswith(".py")
print(result)  # 結果: True

# 実用例:画像ファイルかどうかチェック
filename = "photo.jpg"
image_extensions = [".jpg", ".png", ".gif"]
is_image = any(filename.lower().endswith(ext) for ext in image_extensions)
if is_image:
    print("画像ファイルです")

in演算子で文字がふくまれているか確認

# 基本的な使い方
text = "Python programming"
result = "Python" in text
print(result)  # 結果: True

# 実用例:禁止ワードのチェック
comment = "このサイトは最高です"
bad_words = ["バカ", "アホ", "死ね"]
has_bad_word = any(word in comment for word in bad_words)
if has_bad_word:
    print("不適切な内容がふくまれています")

文字列を分割・結合・置換する

split()で文字列を分割する

# 基本的な使い方
text = "りんご,みかん,バナナ"
fruits = text.split(",")
print(fruits)  # 結果: ['りんご', 'みかん', 'バナナ']

# 実用例:CSVデータの処理
csv_line = "田中,25,東京"
name, age, city = csv_line.split(",")
print(f"名前: {name}, 年齢: {age}, 住所: {city}")

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

# 基本的な使い方
fruits = ["りんご", "みかん", "バナナ"]
result = ",".join(fruits)
print(result)  # 結果: りんご,みかん,バナナ

# 実用例:URLの構築
url_parts = ["https:", "", "example.com", "api", "users"]
url = "/".join(url_parts)
print(url)  # 結果: https://example.com/api/users

replace()で文字を置き換える

# 基本的な使い方
text = "こんにちは、田中さん"
result = text.replace("田中", "佐藤")
print(result)  # 結果: こんにちは、佐藤さん

# 実用例:文字化けの修正
messy_text = "こんにちは!!!"
clean_text = messy_text.replace("!!!", "!")
print(clean_text)  # 結果: こんにちは!

strip()で前後の空白をとりのぞく

# 基本的な使い方
text = "  こんにちは  "
result = text.strip()
print(f"'{result}'")  # 結果: 'こんにちは'

# 実用例:ユーザー入力の整理
user_input = "  tokyo  "
clean_input = user_input.strip().lower()
print(clean_input)  # 結果: tokyo

文字列の内容をチェックする

isnumeric()で数値かどうか確認

# 基本的な使い方
text1 = "123"
text2 = "abc"
print(text1.isnumeric())  # 結果: True
print(text2.isnumeric())  # 結果: False

# 実用例:年齢入力のチェック
age_input = input("年齢を入力してください: ")
if age_input.isnumeric():
    age = int(age_input)
    print(f"あなたは{age}歳ですね")
else:
    print("数値を入力してください")

isalpha()でアルファベットのみか確認

# 基本的な使い方
text1 = "Hello"
text2 = "Hello123"
print(text1.isalpha())  # 結果: True
print(text2.isalpha())  # 結果: False

# 実用例:名前の入力チェック
name = input("名前をローマ字で入力してください: ")
if name.isalpha():
    print(f"こんにちは、{name}さん")
else:
    print("アルファベットのみで入力してください")

count()で文字の出現回数をかぞえる

# 基本的な使い方
text = "banana"
count_a = text.count("a")
print(count_a)  # 結果: 3

# 実用例:パスワードの複雑さチェック
password = "abc123XYZ"
has_numbers = sum(1 for char in password if char.isnumeric()) >= 2
has_uppercase = sum(1 for char in password if char.isupper()) >= 1
if has_numbers and has_uppercase:
    print("強いパスワードです")

便利な整形メソッド

zfill()で0埋めする

# 基本的な使い方
number = "7"
padded = number.zfill(3)
print(padded)  # 結果: 007

# 実用例:ファイル番号の整理
for i in range(1, 11):
    filename = f"file_{str(i).zfill(3)}.txt"
    print(filename)  # file_001.txt, file_002.txt, ...

format()で文字列に値を埋め込む

# 基本的な使い方
name = "田中"
age = 25
message = "私の名前は{}で、{}歳です".format(name, age)
print(message)  # 結果: 私の名前は田中で、25歳です

# f-string(推奨方法)
message = f"私の名前は{name}で、{age}歳です"
print(message)  # 結果: 私の名前は田中で、25歳です

よくある質問と回答

Q: メソッドを使っても元の文字列は変わらないの?
A: はい、文字列は変更できないデータ型です。メソッドは新しい文字列を作って返します。

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

Q: メソッドをつなげて使えるの?
A: はい、メソッドチェーンといって、つなげて使えます。

text = "  Hello World  "
result = text.strip().lower().replace(" ", "_")
print(result)  # 結果: hello_world

Q: エラーが出たときはどうすればいい?
A: よくあるエラーと対処法をおぼえておきましょう。

# AttributeError の例
number = 123
# number.upper()  # エラー!数値にはupperメソッドがない

# 正しくは
text = str(number)
result = text.upper()

まとめ

Pythonの文字列メソッドは、プログラミングでよく使う機能がたくさんつまっています。すべてを一度におぼえる必要はありません。

まず覚えたいメソッド:

  • split() – 文字列を分割
  • join() – リストを結合
  • replace() – 文字を置換
  • strip() – 空白をとりのぞく
  • lower() / upper() – 大文字小文字変換

覚えるコツ:

  1. 実際にコードを書いて試してみる
  2. 日常の作業で使えそうな場面を考える
  3. エラーが出ても慌てず、原因を調べる

コメント

タイトルとURLをコピーしました