Pythonで文字列の末尾から空白を削除するにはどうすればよいですか?


92

文字列内の単語の後の空白を削除する必要があります。これは1行のコードで実行できますか?

例:

string = "    xyz     "

desired result : "    xyz" 

3
この質問は本当にここで尋ねる必要がありましたか?ドキュメントで簡単に見つけることができます:docs.python.org/library/stdtypes.html#str.rstrip
Greg K

11
@Greg Kはい、ドキュメントを読んだ人でさえ、そこにあるかもしれないことに気付いていないかもしれないので、最初の数回はそれを読んだことが基本であると考えて、無関係なことを言っていることを覚えておいてください。さらに、ドキュメント内のrstripは、この問題のGoogle検索で簡単に表示されません(条件「pythonstrip end ofstring」を使用)。
Brōtsyorfuzthrāx

4
本当の寒さ@GregK本当の寒さ
deepelement 2015

回答:



0

次のように、strip()またはsplit()を使用してスペース値を制御できます。

words = "   first  second   "

# remove end spaces
def remove_first_spaces(string):
    return "".join(string.rstrip())


# remove first and end spaces
def remove_first_end_spaces(string):
    return "".join(string.rstrip().lstrip())


# remove all spaces
def remove_all_spaces(string):
    return "".join(string.split())

print(words)
print(remove_first_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))

これがお役に立てば幸いです。

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.