基礎

Pythonの文字列メソッド|split・join・replaceなど頻出操作

文字列(str)はPythonで最も頻繁に扱うデータ型の一つです。Pythonの文字列には、検索・置換・分割・結合など、便利なメソッドが豊富に用意されています。

この記事では、実務でよく使う文字列メソッドを実例付きで詳しく解説します。

基本的な文字列操作

Python
# 大文字・小文字変換
text = "Hello, Python!"
print(text.upper())      # 全て大文字
print(text.lower())      # 全て小文字
print(text.capitalize()) # 先頭だけ大文字
print(text.title())      # 各単語の先頭を大文字
print(text.swapcase())   # 大小反転
実行結果
HELLO, PYTHON!
hello, python!
Hello, python!
Hello, Python!
hELLO, pYTHON!

検索と置換

Python
text = "Python is a great programming language. Python is easy."

# 検索
print(text.find("Python"))       # 最初の位置: 0
print(text.find("Java"))         # 見つからない: -1
print(text.count("Python"))      # 出現回数: 2

# 開始・終了チェック
print(text.startswith("Python")) # True
print(text.endswith("easy."))    # True

# 置換
new_text = text.replace("Python", "JavaScript")
print(new_text)

# 最初の1つだけ置換
new_text = text.replace("Python", "JavaScript", 1)
print(new_text)
実行結果
0
-1
2
True
True
JavaScript is a great programming language. JavaScript is easy.
JavaScript is a great programming language. Python is easy.

分割と結合

split()join()は最も頻繁に使う文字列メソッドです。

Python
# split(): 文字列をリストに分割
sentence = "Python is awesome"
words = sentence.split()  # スペースで分割
print(words)

csv_data = "太郎,25,東京"
fields = csv_data.split(",")
print(fields)

# join(): リストを文字列に結合
words = ["Python", "is", "awesome"]
print(" ".join(words))
print("-".join(words))
print(", ".join(["りんご", "バナナ", "みかん"]))

# splitlines(): 改行で分割
multiline = "1行目
2行目
3行目"
lines = multiline.splitlines()
print(lines)
実行結果
['Python', 'is', 'awesome']
['太郎', '25', '東京']
Python is awesome
Python-is-awesome
りんご, バナナ, みかん
['1行目', '2行目', '3行目']

空白の除去

Python
text = "  Hello, World!  "

print(f"'{text.strip()}'")    # 両端の空白除去
print(f"'{text.lstrip()}'")   # 左側の空白除去
print(f"'{text.rstrip()}'")   # 右側の空白除去

# 指定文字の除去
url = "https://example.com/"
print(url.rstrip("/"))
実行結果
'Hello, World!'
'Hello, World!  '
'  Hello, World!'
https://example.com

判定メソッド

Python
# 文字種の判定
print("123".isdigit())      # 数字のみ: True
print("abc".isalpha())      # 文字のみ: True
print("abc123".isalnum())   # 英数字: True
print("   ".isspace())      # 空白のみ: True
print("Hello".isupper())    # 全て大文字: False
print("hello".islower())    # 全て小文字: True

# 実用例:入力値の検証
user_input = "12345"
if user_input.isdigit():
    print(f"数値として処理: {int(user_input)}")
else:
    print("数値を入力してください")
実行結果
True
True
True
True
False
True
数値として処理: 12345
文字列はイミュータブル

Pythonの文字列は変更不可(イミュータブル)です。replace()upper()などのメソッドは元の文字列を変更せず、新しい文字列を返します。結果を使いたい場合は変数に代入しましょう。

実践的な使い方

Python
# CSVデータの解析
csv_text = "名前,年齢,都市
太郎,25,東京
花子,30,大阪
次郎,22,名古屋"

lines = csv_text.splitlines()
header = lines[0].split(",")

for line in lines[1:]:
    values = line.split(",")
    for h, v in zip(header, values):
        print(f"  {h}: {v}")
    print("---")
実行結果
  名前: 太郎
  年齢: 25
  都市: 東京
---
  名前: 花子
  年齢: 30
  都市: 大阪
---
  名前: 次郎
  年齢: 22
  都市: 名古屋
---

まとめ

  • split()で分割、join()で結合が最頻出
  • replace()で置換、find()/count()で検索
  • strip()で前後の空白を除去
  • isdigit()/isalpha()等で文字種を判定できる
  • 文字列メソッドは元の文字列を変更せず新しい文字列を返す