Open In App

Python | Word location in String

Last Updated : 09 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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(). 

Python3




# 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))


Output : 

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

Time Complexity: O(n), where n is the length of the input string test_str. 
Auxiliary Space: O(n), because we are splitting the input string into a list of words, which takes up O(n) space.

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

Python3




# 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))


Output : 

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

Time Complexity: O(n)
Auxiliary Space : O(n)

Method #3: Using split() and index() methods

Python3




# Python3 code to demonstrate working of
# Word location in String
 
 
# initializing string
test_str = 'geeksforgeeks is best for geeks'
 
# printing original string
print("The original string is : " + test_str)
 
# initializing word
wrd = 'best'
 
x=test_str.split()
res=x.index(wrd)+1
 
# printing result
print("The location of word is : " + str(res))


Output

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

Time Complexity: O(n)
Auxiliary Space : O(n)

Method #4: Using in operator: 

Python3




test_str = 'geeksforgeeks is best for geeks'
wrd = 'best'
# printing original string
print("The original string is : " + test_str)
if wrd in test_str.split():
    res = test_str.split().index(wrd) + 1
else:
    res = -1
print("The location of word is : " + str(res))
 
 
#This code is contributed by Jyothi pinjala


Output

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

Time Complexity: O(n)
Auxiliary Space : O(n)

Method 5: Using the split() method and a list comprehension:

This approach splits the test string into words using the split() method, creates a list of indices where the word appears using a list comprehension, and adds 1 to each index to account for 0-based indexing. If the list of indices is not empty, it sets the result to the first index in the list. Otherwise, it sets the result to -1.

Python3




# Set a test string and the word to be searched
test_str = 'geeksforgeeks is best for geeks'
wrd = 'best'
 
# Split the test string into words, create a list of indices where the word appears, and add 1 to each index (to account for 0-based indexing)
indices = [i+1 for i, word in enumerate(test_str.split()) if word == wrd]
 
# If the list of indices is not empty, set the result to the first index in the list
# Otherwise, set the result to -1
if indices:
    res = indices[0]
else:
    res = -1
 
# Print the result
print("The location of word is : " + str(res))


Output

The location of word is : 3

Time complexity: O(n), where n is the length of the test string (due to the need to split the string and create a list of indices using a list comprehension)
Auxiliary space: O(n) (since the method creates a list of indices)

Method #6: Using a loop to iterate over the words in the string

Split the test string into words, and then iterate over the words to find the index of the first occurrence of the word we are searching for. If we find the word, we can return the index (plus 1 to account for 0-based indexing). If we reach the end of the loop without finding the word, we can return -1.

Python3




# Set a test string and the word to be searched
test_str = 'geeksforgeeks is best for geeks'
wrd = 'best'
 
# Split the test string into words
words = test_str.split()
 
# Iterate over the words to find the index of the first occurrence of the word we are searching for
for i, word in enumerate(words):
    if word == wrd:
        res = i + 1
        break
else:
    res = -1
 
# Print the result
print("The location of word is : " + str(res))


Output

The location of word is : 3

Time complexity:  O(n), where n is the number of words in the test string, because we need to iterate over each word in the string. 
Auxiliary space: O(1), because we only need to store the variables used in the loop.



Similar Reads

Python program to read file word by word
Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file word by word. Read file word by wordIn this article, we will look at how to read a text file and split it into single words using Python. Here are a few examples of reading a file word by word in Python for a bette
2 min read
Python Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap"Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”
4 min read
Python | Get a google map image of specified location using Google Static Maps API
Google Static Maps API lets embed a Google Maps image on the web page without requiring JavaScript or any dynamic page loading. The Google Static Maps API service creates the map based on URL parameters sent through a standard HTTP request and returns the map as an image one can display on the web page. To use this service, one must need an API key
2 min read
Python | Reverse Geocoding to get location on a map using geographic coordinates
Reverse geocoding is the process of finding a place or a location address from a given pair of geographic coordinates(latitude and longitude).Modules needed: reverse_geocoder: A Python library for offline reverse geocoding. pprint: A module which helps to "pretty-print" any arbitrary python data structure. Installation: The modules can be easily in
1 min read
Python | Convert location coordinates to tuple
Sometimes, while working with locations, we need a lot of data which has location points in form of latitudes and longitudes. These can be in form of a string and we desire to get tuple versions of same. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + float() + split() + map() The combination of above fun
5 min read
location element method - Selenium Python
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout - Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What
2 min read
Find the location with specified latitude and longitude using Python
In this article, we are going to write a python script to find the address of a specified latitude and longitude using the geopy module. The geopy module makes it easier to locate the coordinates of addresses, cities, countries, landmarks, and zipcode. Installation: To install GeoPy module, run the following command in your terminal. pip install ge
1 min read
Python Tweepy - Getting the location of a user
In this article we will see how we can get the location of a user. The location of the user account need not be the exact physical location of the user. As the user is free to change their location, the location of the account can even by a hypothetical place. The location attribute is optional and is Nullable. Identifying the location in the GUI :
2 min read
Get Time Zone of a Given Location using Python
In this article, we are going to see how to get the time zone from a given location. The Timezonefinder module is able to find the timezone of any point on earth (coordinates) offline. Before starting we need to install this module. Modules Neededtimezonefinder: This module does not built in with Python. To install this type the below command in th
2 min read
Get Zip Code with given location using GeoPy in Python
In this article, we are going to write a python script to get the Zip code by using location using the Geopy module.geopy makes it easy for Python developers to locate the coordinates of addresses, cities, countries, and landmarks across the world. To install the Geopy module, run the following command in your terminal. pip install geopy Approach:
2 min read
Practice Tags :
three90RightbarBannerImg