Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find index of an exact word in a string in Python [duplicate]

Tags:

python

find

word

word = 'laugh'    
string = 'This is laughing laugh'
index = string.find ( word )

index is 8, should be 17. I looked around hard, but could not find an answer.

like image 221
Khan Avatar asked Aug 15 '16 13:08

Khan


People also ask

How do I find the index of a word in a string?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

How do you see the index of a string in Python?

String Indexing Individual characters in a string can be accessed by specifying the string name followed by a number in square brackets ( [] ). String indexing in Python is zero-based: the first character in the string has index 0 , the next has index 1 , and so on.


2 Answers

You should use regex (with word boundary) as str.find returns the first occurrence. Then use the start attribute of the match object to get the starting index.

import re

string = 'This is laughing laugh'

a = re.search(r'\b(laugh)\b', string)
print(a.start())
>> 17

You can find more info on how it works here.

like image 127
DeepSpace Avatar answered Oct 08 '22 08:10

DeepSpace


try this:

word = 'laugh'    
string = 'This is laughing laugh'.split(" ")
index = string.index(word)

This makes a list containing all the words and then searches for the relevant word. Then I guess you could add all of the lengths of the elements in the list less than index and find your index that way

position = 0
for i,word in enumerate(string):
    position += (1 + len(word))
    if i>=index:
        break

print position  

Hope this helps.

like image 34
Daniel Lee Avatar answered Oct 08 '22 08:10

Daniel Lee