我需要在字符串中单词后面删除空格。能否用一行代码完成?
示例:
示例:
string = " xyz "
desired result : " xyz"
string = " xyz "
desired result : " xyz"
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"
希望这有所帮助。
strip()
еҸҜд»ҘеҗҢж—¶е®ҢжҲҗrstrip()
е’Ңlstrip()
зҡ„еҠҹиғҪпјҢеӣ жӯӨеңЁдҪҝз”Ёж—¶ж— йңҖеҲҶеҲ«дҪҝз”ЁиҝҷдёӨдёӘеҮҪж•°гҖӮиҜ·жіЁж„ҸпјҢзҝ»иҜ‘з»“жһңж—ЁеңЁдҝқжҢҒеҺҹж„ҸпјҢжӣҙжҳ“дәҺзҗҶи§ЈпјҢдёҚеҢ…еҗ«и§ЈйҮҠжҲ–е…¶д»–дҝЎжҒҜгҖӮ - autonopy