I am writing a code that prompts the user to enter a sentence which is then defined as str1 and then is prompted to enter a word defined as str2.
For example:
Please enter a sentence: i like to code in python and code things
Thank you, you entered: i like to code in python and code things
Please enter a word: code
I want to use a for loop to find str2 in str1 and for it to print whether the word has/has not been found and if it has been found, the index position(s) of str2.
Currently i have this code:
str1Input = input("Please enter a sentence: ")
print("Thank you, you entered: ",str1Input)
str1 = str1Input.split()
str2 = input("Please enter a word: ")
for eachWord in str1:
if str2 in str1:
print("That word was found at index position", str1.index(str2)+1)
else:
print("Sorry that word was not found")
Although the outcome appears to print whether or not the word was found with the index value of the word inside str1 once for each word in the sentence? For instance, if str1 was "apples oranges lemons limes pears" and i chose the word "apples" it would come up with:
That word was found at index position: 1
That word was found at index position: 1
That word was found at index position: 1
That word was found at index position: 1
That word was found at index position: 1
If anyone could help me and anyone else attempting something similar to this that would be extremely helpful! Thanks! :)
cancanand are searching for the wordcan. You also us the loopfor eachWord in str1:and then never useeachWord! You are doing the same search on each iteration.