Ask 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. 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

+2
Answers (1)
  1. 31 December, 16:04
    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 & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers