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

Respuesta :

Answer:

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

fichoh

The required function to obtain the nth word of a sentence is stated below :

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

The split function allows strings to be broken down or seperated into distinct parts based on a stated delimiter or seperator such as (comma(,), hypen(-), whitespace) and so on.

In programming indexing starts from 0, hence, the first value is treated as being in position 0.

To obtain value 4th word in a sentence, it will be regarded as being in position 3.

To split the words in the sentence above, the string will be split based on whitespace(space in between each word).

By default this can be achieved without passing any argument to the split method.

That is ; str.split()

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

#This will print lesson (position 3) counting from 0

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

# This won't print anything as it does not meet the first if condition

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

#This will print Now(position 0) counting from 0.

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

#This won't print anything as it does not meet the second if condition (n is more than the number of words in the sentence(4)

Learn more : https://brainly.com/question/17615351

Q&A Education