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