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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With