PYTHON MEBY

Pythonで文字列の先頭・末尾の空白を削除(strip, lstrip, rstrip)

この記事では、Pythonの文字列操作において、文字列の先頭・末尾の空白を削除する3つのメソッドstrip(), lstrip(), rstrip()について解説します。それぞれのメソッドの機能と使い分け、そしてサンプルコードを通して理解を深めます。

目次

strip(): 先頭と末尾の空白を削除

strip()メソッドは、文字列の先頭と末尾にある空白文字を削除します。空白文字には、スペース、タブ、改行文字などが含まれます。

string1 = " \t\nHello, World!\t\n "
string2 = string1.strip()
print(string1) # 出力:  \t\nHello, World!\t\n 
print(string2) # 出力: Hello, World!

上の例では、string1の先頭と末尾の空白文字(スペース、タブ、改行)がstrip()メソッドによって削除され、string2に格納されています。

string = "  Hello, Python!  "
stripped_string = string.strip()
print(f"元の文字列: '{string}'")
print(f"strip()後の文字列: '{stripped_string}'")

実行結果: 元の文字列: ' Hello, Python! ' strip()後の文字列: 'Hello, Python!'

lstrip(): 先頭の空白を削除

lstrip()メソッドは、文字列の先頭にある空白文字を削除します。

string = " \t\nHello, World!"
lstripped_string = string.lstrip()
print(f"元の文字列: '{string}'")
print(f"lstrip()後の文字列: '{lstripped_string}'")

実行結果: 元の文字列: ' \t\nHello, World!' lstrip()後の文字列: 'Hello, World!'

rstrip(): 末尾の空白を削除

rstrip()メソッドは、文字列の末尾にある空白文字を削除します。

string = "Hello, World!\t\n "
rstripped_string = string.rstrip()
print(f"元の文字列: '{string}'")
print(f"rstrip()後の文字列: '{rstripped_string}'")

実行結果: 元の文字列: 'Hello, World!\t\n ' rstrip()後の文字列: 'Hello, World!'

空白文字の種類

strip(), lstrip(), rstrip()メソッドは、スペース、タブ、改行文字だけでなく、Unicodeの空白文字も削除します。

  • \t: タブ文字
  • \n: 改行文字
  • その他Unicodeの空白文字も削除される

実践例

ユーザー入力などから取得した文字列の先頭・末尾の空白を削除する際に、これらのメソッドが役立ちます。

user_input = input("何か入力してください: ")
cleaned_input = user_input.strip()
print(f"入力された文字列: '{user_input}'")
print(f"クリーニング後の文字列: '{cleaned_input}'")

ユーザーが入力した文字列に含まれる不要な空白を削除し、データ処理の精度を高めることができます。

関連記事