我需要删除字符串中单词后面的空格.这可以在一行代码中完成吗?
例:
string = " xyz "
desired result : " xyz"
Run Code Online (Sandbox Code Playgroud)
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)
我希望这有帮助。
| 归档时间: |
|
| 查看次数: |
105419 次 |
| 最近记录: |