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

I have a little problem with something I need to do at school ...

My task is to get the raw input line from the user ( text = raw_input() ) and I need to print the first and last words of this line.

Can someone help me? I searched for an answer all day ...

+6
source share
5 answers

You must first convert the string to a list words using str.split , and then you can access it, for example:

 >>> my_str = "Hello SO user, How are you" >>> word_list = my_str.split() # list of words # first word vv last word >>> word_list[0], word_list[-1] ('Hello', 'you') 

From Python 3.x, you can simply:

 >>> first, *middle, last = my_str.split() 
+11
source

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

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

All words except the first and last will be included in the middle variable.

+7
source

Let's say x is your input. Then you can:

  x.partition(' ')[0] x.partition(' ')[-1] 
+5
source

You would do:

 print text.split()[0], text.split()[-1] 
+1
source

Some may say that there are never too many answers using regular expressions (in this case, it looks like the worst solutions ..):

 >>> import re >>> string = "Hello SO user, How are you" >>> matches = re.findall(r'^\w+|\w+$', string) >>> print(matches) ['Hello', 'you'] 
+1
source

Source: https://habr.com/ru/post/1013300/


All Articles