17

With:

sentence= input("Enter a sentence")
keyword= input("Input a keyword from the sentence")

I want to find the position of the keyword in the sentence. So far, I have this code which gets rid of the punctuation and makes all letters lowercase:

punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''#This code defines punctuation
#This code removes the punctuation
no_punct = "" 
for char in sentence:
   if char not in punctuations:
       no_punct = no_punct + char

no_punct1 =(str.lower (no_punct)

I know need a piece of code which actually finds the position of the word.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Erjonk2001
  • 171
  • 1
  • 1
  • 5
  • 1
    FWIW, you don't need to define your own `punctuations` string: it's already defined in [string.punctuation](https://docs.python.org/3/library/string.html#string.punctuation), along with other useful character subsets. However, you probably don't need to strip punctuation from your sentence, but you may want to strip it from the keyword. BTW, the usual way to call a method is like `no_punct.lower()` _not_ `str.lower(no_punct)` – PM 2Ring Oct 10 '15 at 12:03

2 Answers2

34

This is what str.find() is for :

sentence.find(word)

This will give you the start position of the word (if it exists, otherwise -1), then you can just add the length of the word to it in order to get the index of its end.

start_index = sentence.find(word)
end_index = start_index + len(word) # if the start_index is not -1
Mazdak
  • 105,000
  • 18
  • 159
  • 188
4

If with position you mean the nth word in the sentence, you can do the following:

words = sentence.split(' ')
if keyword in words:
    pos = words.index(keyword)

This will split the sentence after each occurence of a space and save the sentence in a list (word-wise). If the sentence contains the keyword, list.index() will find its position.

EDIT:

The if statement is necessary to make sure the keyword is in the sentence, otherwise list.index() will raise a ValueError.

paolo
  • 2,528
  • 3
  • 17
  • 25
  • This will have issues if the word is the last word in a sentence and followed by a full-stop. – Coddy Feb 25 '22 at 16:24