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

Khan picture Khan · Aug 15, 2016 · Viewed 52.4k times · Source
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.

Answer

DeepSpace picture DeepSpace · Aug 15, 2016

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.