Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the position of a word in a string

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.

like image 665
Erjonk2001 Avatar asked Oct 10 '15 11:10

Erjonk2001


People also ask

How do you find the position of a word in a string?

Python String find() method returns the lowest index or first occurrence of the substring if it is found in a given string. If it is not found, then it returns -1. Parameters: sub: Substring that needs to be searched in the given string.

How do you find the position of a letter in a string in Python?

Get position of a character in String using find() method In this technique, to get the position of a character in a string in Python we will use the find() method. It is a built in method of string class, which takes a character whose position needs to be found out as a parameter.

Which function is used to find the position of a character in a string?

The INSTR function searches a character string for a specified substring, and returns the character position in that string where an occurrence of that a substring ends, based on a count of substring occurrences.


2 Answers

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
like image 180
Mazdak Avatar answered Sep 22 '22 05:09

Mazdak


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.

like image 28
paolo Avatar answered Sep 20 '22 05:09

paolo