Ask Question
30 April, 07:09

Using the "split" string method from the preceding lesson, complete the get_word function to return the {n}th word from a passed sentence. For example, get_word ("This is a lesson about lists", 4) should return "lesson", which is the 4th word in this sentence. Hint: remember that list indexes start at 0, not 1.

def get_word (sentence, n):

# Only proceed if n is positive

if n > 0:

words = ___

# Only proceed if n is not more than the number of words

if n < = len (words):

return (___)

return ("")

print (get_word ("This is a lesson about lists", 4)) # Should print: lesson

print (get_word ("This is a lesson about lists", - 4)) # Nothing

print (get_word ("Now we are cooking!", 1)) # Should print: Now

print (get_word ("Now we are cooking!", 5)) # Nothing

+3
Answers (1)
  1. 30 April, 10:07
    0
    def get_word (sentence, n):

    # Only proceed if n is positive

    if n > 0:

    words = sentence. split ()

    # Only proceed if n is not more than the number of words

    if n < = len (words):

    return words[n-1]

    return (" ")

    print (get_word ("This is a lesson about lists", 4)) # Should print: lesson

    print (get_word ("This is a lesson about lists", - 4)) # Nothing

    print (get_word ("Now we are cooking!", 1)) # Should print: Now

    print (get_word ("Now we are cooking!", 5)) # Nothing

    Explanation:

    Added parts are highlighted.

    If n is greater than 0, split the given sentence using split method and set it to the words.

    If n is not more than the number of words, return the (n-1) th index of the words. Since the index starts at 0, (n-1) th index corresponds to the nth word
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “Using the "split" string method from the preceding lesson, complete the get_word function to return the {n}th word from a passed sentence. ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers