Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extract 1st, 2nd and last words from the string using functions?

My program extracts only letters, but not the entire words.

def first_word(sentence):
    return sentence[0]
def second_word(sentence):
    return sentence[1]
def last_word(sentence):
    return sentence[-1]
  
if __name__ == "__main__":
    sentence = "I want to learn python"
    print(first_word(sentence))
    print(second_word(sentence))
    print(last_word(sentence))

The output in example above must be:

I
want
python

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

sentence.split() will return a list of all the words that are separated by whitespace:

def first_word(sentence):
    return sentence.split()[0]
def second_word(sentence):
    return sentence.split()[1]
def last_word(sentence):
    return sentence.split()[-1]

if __name__ == "__main__":
    sentence = "I want to learn python"
    print(first_word(sentence))
    print(second_word(sentence))
    print(last_word(sentence))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading