Python Forum
cant get the code to give me the position of the word
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
cant get the code to give me the position of the word
#1
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 ")
Reply
#2
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
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
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(" ")
I am trying to help you, really, even if it doesn't always seem that way
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Can you give me a code based on the given skeleton code? Bhavika 10 4,006 Mar-22-2020, 10:59 AM
Last Post: buran
  Python with Finance - i have no code but don't do it for me give me tips please Akainu 1 2,391 May-30-2019, 07:57 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020