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

在Python中如何删除字符串末尾的空白?,python,Python,我需要删除字符串中单词后的空格。这可以在一行代码中完成吗 例如: string = " xyz " desired result : " xyz" 中有更多关于rstrip的信息。您可以使用strip()或split()来控制空格值,如下所示:, 下面是一些测试函数: words = " test words " # Remove end spaces def remove_end_spaces(string): retur

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

例如:

string = "    xyz     "

desired result : "    xyz" 
中有更多关于rstrip的信息。

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

words = "   test    words    "

# Remove end spaces
def remove_end_spaces(string):
    return "".join(string.rstrip())


# Remove the 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(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))
print(remove_all_extra_spaces(words))

我希望这有帮助。

这个问题真的需要在这里问吗?这在文档中很容易找到:@Greg K Yes,因为即使是那些读过文档的人也可能没有意识到它可能在那里,因为这是一个基本原理,他们可能在最初几次阅读时就忽略了它,并记住它说了一些无关的话。此外,文档中的rstrip在谷歌搜索这个问题时并不容易出现(使用标准“python strip end of string”)。real cold@GregK real coldIt还增加了普遍的不友好性,这令人遗憾地成为堆栈溢出越来越明显的特征。
words = "   test    words    "

# Remove end spaces
def remove_end_spaces(string):
    return "".join(string.rstrip())


# Remove the 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(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))
print(remove_all_extra_spaces(words))