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

Time:11-16

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

CodePudding user response:

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

CodePudding user response:

Use str.split method:

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

Output:

I
want
python
  • Related