Word location in String - Python
Word location in String problem in Python involves finding the position of a specific word or substring within a given string. This problem can be approached using various methods in Python, such as using the find(), index() methods or by regular expressions with the re module.
Using str.find()
str.find()
find the first occurrence of the target word in the string. If found, it calculates the word’s position by counting the spaces before the word. While it’s efficient, it requires extra operations such as counting spaces to determine the word’s index. If the word is not found, it returns -1
.
s= 'geeksforgeeks is best for geeks'
w= 'best'
pos = s.find(w)
# If word is found, calculate its position
if pos == -1:
res = -1 # Word not found
else:
res = s[:pos].count(' ') + 1 # Count spaces before the word and add 1
print(res)
Output
3
Explanation:
s.find(w)
:This finds the position of the wordw
in the strings
. Returns-1
if not found.if pos == -1
: This checks if the word is not found and setsres
to-1
.s[:pos].count(' ')
: This counts spaces before the word to determine the number of words before it.res = s[:pos].count(' ') + 1
: This adds 1 to get the 1-based index of the word.
Table of Content
Using str.split().index()
This method splits the string into words and directly finds the index of the target word using index(). If the word is found, it returns the position. If the word is not found, it raises a ValueError, which is handled using a try-except block to return -1 in such cases.
s= 'geeksforgeeks is best for geeks'
w= 'best'
# Trying to find the index of the word
try:
res = s.split().index(w) + 1 # 1-based index
except ValueError:
res = -1 # Word not found
print(res)
Output
3
Explanation:
s.split()
: This splits `s` into a list of words.index(w)
: This finds the 0-based index of the target wordw
in the list.+ 1
: This converts the index to 1-based index.except ValueError
: If the word is not found ,-1
is assigned.
Using re.findall()
This method uses regular expressions re.findall() to find the target word in each word of the string, then calls index() to find its position. It iterates over each word in the string and checks for the target word using re.findall(). This approach is less efficient due to the repeated calls to index().
import re
s = 'geeksforgeeks is best for geeks'
w= 'best' # target word
# Splitting the string into words
s = s.split()
# Initializing result variable
res = -1
for i in s:
if len(re.findall(w, i)) > 0:
res = s.index(i) + 1 # Get 1-based index
break # Stop once the word is found
print(res)
Output
3
Explanation:
s.split()
: This splits `s` into a list of words.re.findall(w, i)
: This searches for the target wordw
in each wordi
.s.index(i) + 1
: This finds the index of the wordi
and converts it to 1-based index.break
: This stops the loop once the target word is found.
Using loop
This method finds the position of a word in a string by splitting the string into words and looping through them. It stops as soon as the word is found, making it fast and efficient. If the word is present, it returns its position otherwise it returns -1
.
a = 'geeksforgeeks is best for geeks' # String
w = 'best' # Target word
# Splitting `s` into a list of words
b = a.split()
# Initializing the result variable
res = -1
for i, word in enumerate(b): # 'i' is the index, 'word' is the current word in the list
if word == w:
res = i + 1
break # Stop the loop once the word is found
print(str(res))
Output
3
Explanation:
a.split()
: This splits the string into words.for i, word in enumerate(b)
: Ths loops through the list of words, providing indexi
.if word == w
: This checks if the current word matches the target wordw
.res = i + 1
: Stores the 1-based index of the target word.break
: This stops the loop after finding the word.