😸

Pythonの文字列操作テクニック集

に公開

Pythonで文字列を扱う際に知っておくと便利なテクニックをまとめました。基本から応用まで、実践的なコード例と共に紹介します。

基本的な文字列操作

文字列の結合

# join()を使った効率的な結合
words = ['Python', 'は', '楽しい']
result = ''.join(words)  # 'Pythonは楽しい'

# 区切り文字を指定
result = ' '.join(words)  # 'Python は 楽しい'

ポイント: +演算子による結合よりもjoin()の方が効率的です。

文字列の分割

text = 'apple,banana,orange'

# split()で分割
fruits = text.split(',')  # ['apple', 'banana', 'orange']

# 分割回数を指定
text = 'a:b:c:d'
result = text.split(':', 2)  # ['a', 'b', 'c:d']

# 空白文字で分割
sentence = 'Hello  World  Python'
words = sentence.split()  # ['Hello', 'World', 'Python']

文字列のスライス

text = 'Python Programming'

# 基本的なスライス
print(text[0:6])    # 'Python'
print(text[7:])     # 'Programming'
print(text[:6])     # 'Python'

# ステップを指定
print(text[::2])    # 'Pto rgamn'
print(text[::-1])   # 'gnimmargorP nohtyP' (反転)

文字列の検索と置換

検索メソッド

text = 'Python is powerful and Python is fun'

# 文字列が含まれるか
print('Python' in text)  # True

# 位置を取得
print(text.find('Python'))      # 0 (最初の位置)
print(text.rfind('Python'))     # 23 (最後の位置)
print(text.index('is'))         # 7
print(text.count('Python'))     # 2

# 前方一致・後方一致
print(text.startswith('Python'))  # True
print(text.endswith('fun'))       # True

置換

text = 'I like cats. Cats are cute.'

# 基本的な置換
result = text.replace('cats', 'dogs')
# 'I like dogs. Cats are cute.'

# 置換回数を指定
result = text.replace('cats', 'dogs', 1)
# 'I like dogs. Cats are cute.'

# 大文字小文字を無視した置換(re モジュール使用)
import re
result = re.sub(r'cats', 'dogs', text, flags=re.IGNORECASE)
# 'I like dogs. dogs are cute.'

文字列のフォーマット

f-string(推奨)

name = 'Alice'
age = 25

# 基本的な使い方
message = f'My name is {name} and I am {age} years old'

# 式の埋め込み
print(f'{name.upper()} is {age + 5} years old in 5 years')

# フォーマット指定
pi = 3.14159265359
print(f'Pi is approximately {pi:.2f}')  # 'Pi is approximately 3.14'

# パディング
number = 42
print(f'{number:05d}')  # '00042'

format()メソッド

# 位置引数
print('{} {} {}'.format('a', 'b', 'c'))  # 'a b c'

# インデックス指定
print('{2} {1} {0}'.format('a', 'b', 'c'))  # 'c b a'

# キーワード引数
print('{name} is {age} years old'.format(name='Bob', age=30))

文字列の変換

大文字・小文字の変換

text = 'Python Programming'

print(text.upper())      # 'PYTHON PROGRAMMING'
print(text.lower())      # 'python programming'
print(text.capitalize()) # 'Python programming'
print(text.title())      # 'Python Programming'
print(text.swapcase())   # 'pYTHON pROGRAMMING'

空白の削除

text = '  Python  '

print(text.strip())   # 'Python'
print(text.lstrip())  # 'Python  '
print(text.rstrip())  # '  Python'

# 特定の文字を削除
url = 'https://example.com/'
print(url.rstrip('/'))  # 'https://example.com'

正規表現を使った高度な操作

import re

text = 'Email: user@example.com, Phone: 090-1234-5678'

# パターンマッチング
email_pattern = r'[\w\.-]+@[\w\.-]+'
email = re.search(email_pattern, text)
print(email.group())  # 'user@example.com'

# すべてのマッチを取得
numbers = re.findall(r'\d+', text)
print(numbers)  # ['090', '1234', '5678']

# 分割
parts = re.split(r'[,:]', text)
print(parts)  # ['Email', ' user@example.com', ' Phone', ' 090-1234-5678']

文字列のチェック

# 文字種の判定
print('123'.isdigit())      # True
print('abc'.isalpha())      # True
print('abc123'.isalnum())   # True
print('   '.isspace())      # True
print('Hello'.islower())    # False
print('HELLO'.isupper())    # True

実践的なテクニック

複数行の文字列

# トリプルクォート
text = '''
This is
a multi-line
string
'''

# 行のリストに変換
lines = text.strip().split('\n')

文字列のパディング

text = 'Python'

# 左詰め、右詰め、中央揃え
print(text.ljust(10, '-'))   # 'Python----'
print(text.rjust(10, '-'))   # '----Python'
print(text.center(10, '-'))  # '--Python--'

# zfill(数値の0埋め)
print('42'.zfill(5))  # '00042'

Counterを使った文字数カウント

from collections import Counter

text = 'hello world'
counter = Counter(text)
print(counter)  # Counter({'l': 3, 'o': 2, 'h': 1, ...})

# 最頻出文字
print(counter.most_common(2))  # [('l', 3), ('o', 2)]

文字列の反転

text = 'Python'

# スライスを使う方法
reversed_text = text[::-1]  # 'nohtyP'

# reversed()を使う方法
reversed_text = ''.join(reversed(text))  # 'nohtyP'

まとめ

Pythonの文字列操作は非常に強力で、多くの組み込みメソッドが用意されています。状況に応じて適切なメソッドを選択することで、効率的で読みやすいコードを書くことができます。

覚えておくべきポイント:

  • 文字列の結合にはjoin()を使う
  • f-stringでフォーマットする(Python 3.6+)
  • 複雑なパターンマッチングには正規表現を使う
  • 文字列は不変(immutable)なので、メソッドは新しい文字列を返す

Discussion