Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the first and final words from a string?

I have a small problem with something I need to do in school...

My task is the get a raw input string from a user (text = raw_input()) and I need to print the first and final words of that string.

Can someone help me with that? I have been looking for an answer all day...

like image 571
Lior Dahan Avatar asked Sep 07 '25 12:09

Lior Dahan


2 Answers

You have to firstly convert the string to list of words using str.split and then you may access it like:

>>> my_str = "Hello SO user, How are you"
>>> word_list = my_str.split()  # list of words

# first word  v              v last word
>>> word_list[0], word_list[-1]
('Hello', 'you')

From Python 3.x, you may simply do:

>>> first, *middle, last = my_str.split()
like image 126
Moinuddin Quadri Avatar answered Sep 09 '25 02:09

Moinuddin Quadri


If you are using Python 3, you can do this:

text = input()
first, *middle, last = text.split()
print(first, last)

All the words except the first and last will go into the variable middle.

like image 25
Anand Chitipothu Avatar answered Sep 09 '25 00:09

Anand Chitipothu