Python で文字列内のスペースを削除
Python では、文字列内のスペースを削除するために複数の方法を使用できます。最も一般的な方法はstrip()、lstrip()とrstrip()関数、またはreplace()関数を使用してスペースを置換します。
方法 1: 使用するstrip()関数
strip()関数は、文字列の先頭と末尾のスペースを削除するために使用されます。
例
text = " Hello, World! "
trimmed_text = text.strip()
print(trimmed_text)
trimmed_text = text.strip()
print(trimmed_text)
コードの説明:
text.strip():文字列のtext先頭と末尾のスペースを削除します。print(trimmed_text):スペースを削除した後の文字列を出力します。
出力結果:
Hello, World!
方法 2: 使用するlstrip()とrstrip()関数
lstrip()は、文字列の先頭のスペースを削除するために使用され、rstrip()は、文字列の末尾のスペースを削除するために使用されます。
例
text = " Hello, World! "
left_trimmed_text = text.lstrip()
right_trimmed_text = text.rstrip()
print(left_trimmed_text)
print(right_trimmed_text)
left_trimmed_text = text.lstrip()
right_trimmed_text = text.rstrip()
print(left_trimmed_text)
print(right_trimmed_text)
コードの説明:
text.lstrip():文字列のtext先頭のスペースを削除します。text.rstrip():文字列のtext末尾のスペースを削除します。print(left_trimmed_text):先頭のスペースを削除した後の文字列を出力します。print(right_trimmed_text):末尾のスペースを削除した後の文字列を出力します。
出力結果:
Hello, World! Hello, World!
方法 3: 使用するreplace()関数
replace()関数は、文字列内のスペースを他の文字(または空文字)に置き換えることができます。
例
text = " Hello, World! "
no_spaces_text = text.replace(" ", "")
print(no_spaces_text)
no_spaces_text = text.replace(" ", "")
print(no_spaces_text)
コードの説明:
text.replace(" ", ""):文字列のtext中のすべてのスペースを空文字に置き換えます(つまりスペースを削除します)。print(no_spaces_text):すべてのスペースを削除した後の文字列を出力します。
出力結果:
Hello,World!
方法 4: 使用するsplit()とjoin()関数
split()関数は、文字列をスペースで分割してリストにすることができ、join()関数は、リスト内の要素を連結して1つの文字列にすることができます。
例
text = " Hello, World! "
words = text.split()
no_spaces_text = "".join(words)
print(no_spaces_text)
words = text.split()
no_spaces_text = "".join(words)
print(no_spaces_text)
コードの説明:
text.split():文字列をtextスペースで分割してリストにします。words。"".join(words):リストのwords要素を連結して1つの文字列にします。間にスペースはありません。print(no_spaces_text):連結した後の文字列を出力します。
出力結果:
Hello,World!
これらの方法は、さまざまなニーズに応じて選択して使用できます。文字列の先頭と末尾のスペースだけを削除する必要がある場合は、strip()が最も簡単な選択肢です。文字列内のすべてのスペースを削除する必要がある場合は、replace() 或 split() + join()がより良い選択肢です。
Python3 の例