Said Py
Наурыз 24, 2020, 4:02 Т.Қ.

Python-да жолдан соңғы сөзді қалай жоюға болады

Мазмұны

Чтобы удалить последнее слово из строки, нам нужно выполнить следующие шаги.

  1. преобразовать строку в список с помощью функции split()
  2. удалить последний элемент из списка
  3. преобразовать список в строку

пример

  1. #string
  2. string = "hello world"
  3.  
  4. #split string
  5. spl_string = string.split()
  6.  
  7. #remove the last item in list
  8. rm = spl_string[:-1]
  9.  
  10. #convert list to string
  11. listToStr = ' '.join([str(elem) for elem in rm])
  12.  
  13. #print string
  14. print(listToStr)

вывод

hello

Мақала бойынша сұралады0сұрақтар(лар)

3

Ол саған ұнайды ма? Әлеуметтік желілерде бөлісіңіз!

Evgenii Legotckoi
  • Наурыз 24, 2020, 4:02 Т.Қ.

Thank you, for your example.

ИГ
  • Наурыз 25, 2020, 10:29 Т.Ж.
  1. text = "hello world"
  2. print('' if ' ' not in text else text.rsplit(' ', 1)[0])
  1. # [] излишни
  2. listToStr = ' '.join(str(elem) for elem in rm)
Konstantin Grudnitskiy
  • Сәуір 3, 2020, 4:18 Т.Қ.
  1. >>> text = 'hello world'
  2. >>> ' '.join(word for word in text.split()[:-1])
  3. 'hello'
  4. >>> def remove_last_word(text):
  5. ... return text and ' '.join(word for word in text.split()[:-1])
  6. ...
  7. >>> remove_last_word(None)
  8. >>> remove_last_word('hello')
  9. ''
  10. >>> remove_last_word('hello world')
  11. 'hello'
  12. >>> remove_last_word('some other test string')
  13. 'some other test'

Пікірлер

Тек рұқсаты бар пайдаланушылар ғана пікір қалдыра алады.
Кіріңіз немесе Тіркеліңіз