close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to extract the first and final words from a string in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

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

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

    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

  2. extract the first and final words from a string

    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

Method 1

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()

Method 2

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.

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read