如何从Python中删除字符串末尾的空格?

Pab*_*blo 77 python

我需要删除字符串中单词后面的空格.这可以在一行代码中完成吗?

例:

string = "    xyz     "

desired result : "    xyz" 
Run Code Online (Sandbox Code Playgroud)

Sil*_*ost 147

>>> "    xyz     ".rstrip()
'    xyz'
Run Code Online (Sandbox Code Playgroud)

更多关于rstrip文档


K.A*_*K.A 18

您可以使用 strip() 或 split() 来控制空格值,如下所示,这是一些测试函数:

words = "   test     words    "

# Remove end spaces
def remove_end_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())

# Remove all extra spaces
def remove_all_extra_spaces(string):
    return " ".join(string.split())

# Show results
print(f'"{words}"')
print(f'"{remove_end_spaces(words)}"')
print(f'"{remove_first_end_spaces(words)}"')
print(f'"{remove_all_spaces(words)}"')
print(f'"{remove_all_extra_spaces(words)}"')
Run Code Online (Sandbox Code Playgroud)

输出:

"   test     words    "

"   test     words"

"test     words"

"testwords"

"test words"
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助。

  • 当有一个特定函数同时执行这两个操作时,没有必要使用“rstrip()”和“lstrip()”:“strip()” (5认同)
  • 哦,我看到你拒绝了我的编辑,然后自己做了。似乎“这种编辑为了推销产品或服务而破坏了帖子,或者是故意破坏性的。”毕竟不是真的。 (2认同)