首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Python中删除字符串末尾的空格?

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

Stack Overflow用户
提问于 2010-03-03 23:36:14
回答 2查看 174K关注 0票数 120

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

示例:

string = "    xyz     "

desired result : "    xyz" 
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-03-03 23:37:01

>>> "    xyz     ".rstrip()
'    xyz'

the documentation中有更多关于rstrip的内容。

票数 212
EN

Stack Overflow用户

发布于 2020-11-03 22:48:31

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

我希望这对你有帮助。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2372573

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档