userjake
userjake

Reputation: 11

How would you use a `for` or `while` loop to find the nth word in a sentence

How would you use a for or while loop to find a word in a sentence if the user enter like inputs inputs the sentence and the index of the word in the sentence.

sentence = input('Please enter a sentence: ')
word_number = input ('Please enter word number request: ')

Upvotes: 0

Views: 200

Answers (2)

Cyberguille
Cyberguille

Reputation: 1602

I think that the best option is https://stackoverflow.com/a/62420371/2399444 But it looks like is a requirement for you use For or While

For instance one solution could be

sentence = input('Please enter a sentence: ')
word_number = input('Please enter word number request: ')
words = sentence.split(' ')

for i, word in enumerate(words):
    if(i == word_number-1):
        print(word)
        break
if(word_number > len(words)):
    print('Word not found. Sentence only has', len(words), 'words')

Upvotes: -1

CaffeinatedMike
CaffeinatedMike

Reputation: 1607

sentence = input('Please enter a sentence: ')
word_number = input('Please enter word number request: ')
words = sentence.split(' ')
try:
    # make sure to convert to integer
    # -1 because list indices are 0-based
    print(words[int(word_number)-1])
except IndexError:
    print('Word not found. Sentence only has', len(words), 'words')

Upvotes: 5

Related Questions