Мені потрібно видалити пробіли після слова у рядку. Чи можна це зробити в одному рядку коду?
Приклад:
string = " xyz "
desired result : " xyz"
Мені потрібно видалити пробіли після слова у рядку. Чи можна це зробити в одному рядку коду?
Приклад:
string = " xyz "
desired result : " xyz"
Відповіді:
>>> " xyz ".rstrip()
' xyz'
докладніше про це rstripв документах
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))
Я сподіваюся, це корисно.