Python | Word location in String

Sometimes, while working with Python strings, we can have problem in which we need to find location of a particular word. This can have application in domains such as day-day programming. Lets discuss certain ways in which this task can be done.

Method #1 : Using re.findall() + index()
This is one of the way in which we can find the location where word exists. In this we look for substring pattern using findall() and its position using index().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Word location in String
# Using findall() + index()
import re
  
# initializing string
test_str = 'geeksforgeeks is best for geeks'
  
# printing original string
print("The original string is : " + test_str)
  
# initializing word 
wrd = 'best'
  
# Word location in String
# Using findall() + index()
test_str = test_str.split()
res = -1
for idx in test_str:
    if len(re.findall(wrd, idx)) > 0:
        res = test_str.index(idx) + 1
  
# printing result 
print("The location of word is : " + str(res)) 

chevron_right


Output :

The original string is : geeksforgeeks is best for geeks
The location of word is : 3

 

Method #2 : Using re.sub() + index()
This performs this task in similar way as above method. In this also regex is employed. We use different regex function in this method.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Word location in String
# Using re.sub() + index()
import re
  
# initializing string
test_str = 'geeksforgeeks is best for geeks'
  
# printing original string
print("The original string is : " + test_str)
  
# initializing word 
wrd = 'best'
  
# Word location in String
# Using re.sub() + index()
res = re.sub("[^\w]", " ",  test_str).split()
res = res.index(wrd) + 1
  
# printing result 
print("The location of word is : " + str(res)) 

chevron_right


Output :

The original string is : geeksforgeeks is best for geeks
The location of word is : 3



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.