Python strip()の使い方:文字列のトリミング処理を解説
Pythonでは、strip()関数は文字列の両端から指定された文字(デフォルトは空白)または空白文字を取り除くために使用されます。strip()関数を使用する方法は以下の通りです:
- 両端の空白を取り除くために、デフォルトのスペース文字を使用します。
s = " hello world "
print(s.strip()) # Output: "hello world"
- 特定の削除する文字:
s = "!!!hello world!!!"
print(s.strip("!")) # Output: "hello world"
- 指定された文字セットを削除する:
s = "!!!hello world!!!"
print(s.strip("!d")) # Output: "hello worl"
strip()関数は新しい文字列を返しますが、元の文字列は変更されません。