close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to find index of an exact word in a string in Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

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

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

    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.

  2. find index of an exact word in a string in Python

    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.

Method 1

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

Method 2

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.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read