Python Forum
cant get the code to give me the position of the word - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: cant get the code to give me the position of the word (/thread-5875.html)



cant get the code to give me the position of the word - axius23 - Oct-25-2017

Hi i have a problem with my homework i cant get the code to give me the pisition of the word.
The question is :
Develop a program that analyses a sentence that contains several words without punctuation. When a word in that sentence is input, the program identifies all of the positions where the word occurs in the sentence. The system should not be case sensitive: Ask, ask, ASK should be treated as the same word.
For example, in the sentence “ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY”
The word ‘COUNTRY’ occurs in the 5th and 17th positions.

sentence = input("write a long sentence please ")
sentence.split(" ")

palabra = input("Please enter a word from the sentance and the position of the word you typed in will be displayed on the screen ")

if palabra in sentence:
    print("we have found the word u are looking for ")
else:
    print("The word you are looking for it's not in the sentence ")



RE: homework - wavic - Oct-25-2017

Hello!
Since there is no punctuation you can just split the sentence to create a list of all of the words and check the index of the matched word. Then add 1 because indexing starts from 0.
For example


RE: homework - gruntfutuk - Oct-27-2017

Use .lower() to make sure the input strings are in lower case (or apply it to the test).

You could use something like this:
positions = []
for position, aword in enumerate(words):
    if aword == word:
        positions.append(position + 1)
which will give you an array of the word positions the search word was found at. If the array is empty, no matches were found. You can use join() to print the array with commas between the positions (although note that join expects strings not integers).

Note that sentence.split(" ") is handy in the console,
but does not store the output unless you assign it,
e.g. words = sentence.split(" ")