我需要删除字符串中单词后面的空格。这可以在一行代码中完成吗?
示例:
string = " xyz "
desired result : " xyz"
发布于 2010-03-03 23:37:01
>>> " xyz ".rstrip()
' xyz'
在the documentation中有更多关于rstrip
的内容。
发布于 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"
我希望这对你有帮助。
https://stackoverflow.com/questions/2372573
复制相似问题