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

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

例如:

string = "    xyz     "


desired result : "    xyz"
214257 次浏览
>>> "    xyz     ".rstrip()
'    xyz'

文件中有更多关于 rstrip的内容。

您可以使用 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)}"')

产出:

"   test     words    "


"   test     words"


"test     words"


"testwords"


"test words"

我希望这能帮上忙。