Tôi cần xóa khoảng trắng sau từ trong chuỗi. Điều này có thể được thực hiện trong một dòng mã không?
Thí dụ:
string = " xyz "
desired result : " xyz"
Tôi cần xóa khoảng trắng sau từ trong chuỗi. Điều này có thể được thực hiện trong một dòng mã không?
Thí dụ:
string = " xyz "
desired result : " xyz"
Câu trả lời:
>>> " xyz ".rstrip()
' xyz'
thêm về rstriptrong tài liệu
words = " first second "
# remove end spaces
def remove_first_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())
print(words)
print(remove_first_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))
tôi hy vọng điều này hữu ích.