Pythonで文字列の一部を削除する方法:strip, lstrip, rstripの使い方
strip()メソッドによる両端削除
基本的な空白文字の削除
text = " Hello, World! "
cleaned = text.strip()
print(f"'{cleaned}'") # 'Hello, World!'
# 元の文字列は変更されない
print(f"'{text}'") # ' Hello, World! '
改行文字やタブ文字の削除
text = "\n\t Hello, World! \t\n"
cleaned = text.strip()
print(repr(cleaned)) # 'Hello, World!'
特定の文字を削除
text = "xxxHello, World!xxx"
cleaned = text.strip('x')
print(cleaned) # Hello, World!
# 複数の文字を指定
text = ".,!Hello, World!,.!"
cleaned = text.strip('.,!')
print(cleaned) # Hello, World
lstrip()メソッドによる左端削除
左側の空白文字削除
text = " Hello, World!"
left_stripped = text.lstrip()
print(f"'{left_stripped}'") # 'Hello, World!'
左側の特定文字削除
url = "https://www.example.com"
without_protocol = url.lstrip('https://')
print(without_protocol) # www.example.com
# 文字集合として削除
text = "000123000"
cleaned = text.lstrip('0')
print(cleaned) # 123000
rstrip()メソッドによる右端削除
右側の空白文字削除
text = "Hello, World! "
right_stripped = text.rstrip()
print(f"'{right_stripped}'") # 'Hello, World!'
右側の特定文字削除
filename = "document.txt.bak"
without_bak = filename.rstrip('.bak')
print(without_bak) # document.txt
# 改行文字の削除
line = "Hello, World!\n"
cleaned = line.rstrip('\n')
print(repr(cleaned)) # 'Hello, World!'
実用的な活用例
ファイル読み込み時の改行削除
def read_lines_clean(filename):
"""ファイルを読み込み、各行の改行文字を削除"""
with open(filename, 'r', encoding='utf-8') as file:
return [line.rstrip('\n\r') for line in file]
# または
def read_lines_clean2(filename):
with open(filename, 'r', encoding='utf-8') as file:
return [line.strip() for line in file if line.strip()]
CSVデータの前後空白削除
csv_line = " 田中 , 30 , エンジニア , 東京 "
# 分割後に各要素をstrip
fields = [field.strip() for field in csv_line.split(',')]
print(fields) # ['田中', '30', 'エンジニア', '東京']
URLの正規化
def normalize_url(url):
"""URLから不要な文字を削除して正規化"""
# プロトコルを削除
url = url.lstrip('http://').lstrip('https://')
# 末尾のスラッシュを削除
url = url.rstrip('/')
# www.プレフィックスを削除
url = url.lstrip('www.')
return url
urls = [
"https://www.example.com/",
"http://example.com",
"www.example.com/"
]
for url in urls:
print(f"{url} → {normalize_url(url)}")
パスワードの前後空白除去
def validate_password(password):
"""パスワードの前後空白を除去してバリデーション"""
cleaned_password = password.strip()
if len(cleaned_password) < 8:
return False, "パスワードは8文字以上で入力してください"
if cleaned_password != password:
return False, "パスワードの前後に空白が含まれています"
return True, "有効なパスワードです"
passwords = ["password123", " password123", "password123 ", " password123 "]
for pwd in passwords:
valid, message = validate_password(pwd)
print(f"'{pwd}': {message}")
複数の文字や文字列の削除
removeprefix()とremovesuffix()(Python 3.9+)
# Python 3.9以降
text = "HelloWorld"
without_hello = text.removeprefix("Hello")
print(without_hello) # World
text = "filename.txt"
without_ext = text.removesuffix(".txt")
print(without_ext) # filename
互換性のあるカスタム関数
def remove_prefix(text, prefix):
"""Python 3.8以下でも動作するremoveprefix"""
if text.startswith(prefix):
return text[len(prefix):]
return text
def remove_suffix(text, suffix):
"""Python 3.8以下でも動作するremovesuffix"""
if text.endswith(suffix):
return text[:-len(suffix)]
return text
text = "HelloWorld"
print(remove_prefix(text, "Hello")) # World
print(remove_suffix("filename.txt", ".txt")) # filename
正規表現による削除
先頭・末尾のパターン削除
import re
def strip_pattern(text, pattern):
"""正規表現パターンを両端から削除"""
# 先頭から削除
text = re.sub(f'^{pattern}+', '', text)
# 末尾から削除
text = re.sub(f'{pattern}+$', '', text)
return text
text = "123Hello World456"
cleaned = strip_pattern(text, r'\d')
print(cleaned) # Hello World
複雑なパターンの削除
import re
def clean_text(text):
"""テキストから不要な文字を削除"""
# HTMLタグを削除
text = re.sub(r'<[^>]+>', '', text)
# 複数の空白を1つに
text = re.sub(r'\s+', ' ', text)
# 前後の空白を削除
text = text.strip()
return text
html_text = "<p> Hello, <strong>World</strong>! </p>"
cleaned = clean_text(html_text)
print(cleaned) # Hello, World!
条件付きの削除
特定の条件でのみ削除
def conditional_strip(text, chars, condition=lambda x: True):
"""条件を満たす場合のみ文字を削除"""
if condition(text):
return text.strip(chars)
return text
def is_quoted(text):
"""文字列が引用符で囲まれているかチェック"""
return (text.startswith('"') and text.endswith('"')) or \
(text.startswith("'") and text.endswith("'"))
texts = ['"Hello, World!"', "'Python'", "Normal text"]
for text in texts:
cleaned = conditional_strip(text, '"\'', is_quoted)
print(f"{text} → {cleaned}")
パフォーマンス比較
import time
import re
def benchmark_strip_methods():
text = " " + "Hello World" * 1000 + " "
iterations = 10000
# strip()メソッド
start = time.time()
for _ in range(iterations):
result = text.strip()
time1 = time.time() - start
# 正規表現
pattern = re.compile(r'^\s+|\s+$')
start = time.time()
for _ in range(iterations):
result = pattern.sub('', text)
time2 = time.time() - start
# 手動実装
start = time.time()
for _ in range(iterations):
start_idx = 0
end_idx = len(text)
while start_idx < end_idx and text[start_idx].isspace():
start_idx += 1
while end_idx > start_idx and text[end_idx-1].isspace():
end_idx -= 1
result = text[start_idx:end_idx]
time3 = time.time() - start
print(f"strip(): {time1:.6f}秒")
print(f"正規表現: {time2:.6f}秒")
print(f"手動実装: {time3:.6f}秒")
benchmark_strip_methods()
エラーハンドリングと注意点
def safe_strip(text, chars=None):
"""None値に対応した安全なstrip"""
if text is None:
return None
try:
if chars is None:
return text.strip()
else:
return text.strip(chars)
except AttributeError:
# textが文字列でない場合
return str(text).strip(chars) if chars else str(text).strip()
# テスト
values = [" hello ", None, 123, " world "]
for value in values:
print(f"{value} → {safe_strip(value)}")
複数行文字列の処理
def strip_multiline(text, strip_empty_lines=True):
"""複数行文字列の各行をstrip"""
lines = text.splitlines()
stripped_lines = [line.strip() for line in lines]
if strip_empty_lines:
stripped_lines = [line for line in stripped_lines if line]
return '\n'.join(stripped_lines)
multiline = """
Hello, World!
Python Programming
"""
cleaned = strip_multiline(multiline)
print(repr(cleaned))
まとめ
文字列の削除処理は用途に応じて適切なメソッドを選択することが重要です:
- 基本的な空白削除:
strip()
,lstrip()
,rstrip()
- 特定の文字削除:引数付きstrip系メソッド
- プレフィックス・サフィックス削除:
removeprefix()
,removesuffix()
- 複雑なパターン:正規表現
- 条件付き削除:カスタム関数
これらを適切に使い分けることで、効率的な文字列処理が実現できます。
■プロンプトだけでオリジナルアプリを開発・公開してみた!!
■AI時代の第一歩!「AI駆動開発コース」はじめました!
テックジム東京本校で先行開始。
■テックジム東京本校
「武田塾」のプログラミング版といえば「テックジム」。
講義動画なし、教科書なし。「進捗管理とコーチング」で効率学習。
より早く、より安く、しかも対面型のプログラミングスクールです。
<短期講習>5日で5万円の「Pythonミニキャンプ」開催中。
<月1開催>放送作家による映像ディレクター養成講座
<オンライン無料>ゼロから始めるPython爆速講座