Word location in String - Python Last Updated : 11 Jan, 2025 Comments Improve Suggest changes Like Article Like Report 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. Python 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) Output3 Explanation:s.find(w):This finds the position of the word w in the string s. Returns -1 if not found.if pos == -1: This checks if the word is not found and sets res 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 ContentUsing str.split().index()Using str.find()Using re.findall() 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. Python 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) Output3 Explanation:s.split(): This splits `s` into a list of words.index(w): This finds the 0-based index of the target word w 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(). Python 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) Output3 Explanation:s.split(): This splits `s` into a list of words.re.findall(w, i): This searches for the target wordwin each word i.s.index(i) + 1: This finds the index of the word i 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. Python 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)) Output3 Explanation:a.split(): This splits the string into words.for i, word in enumerate(b): Ths loops through the list of words, providing index i .if word == w: This checks if the current word matches the target word w.res = i + 1: Stores the 1-based index of the target word.break: This stops the loop after finding the word. Comment More infoAdvertise with us Next Article Word location in String - Python manjeet_04 Follow Improve Article Tags : Python Python Programs Python string-programs Practice Tags : python Similar Reads Python - Words Lengths in String We are given a string we need to find length of each word in a given string. For example, we are s = "Hello world this is Python" we need to find length of each word so that output should be a list containing length of each words in sentence, so output in this case will be [5, 5, 4, 2, 6].Using List 2 min read Python - Word starting at Index Sometimes, while working with Python, we can have a problem in which we need to extract the word which is starting from a particular index. This can have a lot of applications in school programming. Let's discuss certain ways in which this task can be performed. Method #1: Using a loop This is a bru 2 min read Python - Get Nth word in given String Sometimes, while working with data, we can have a problem in which we need to get the Nth word of a String. This kind of problem has many application in school and day-day programming. Let's discuss certain ways in which this problem can be solved. Method #1 : Using loop This is one way in which thi 4 min read Python - List Words Frequency in String Given a List of Words, Map frequency of each to occurrence in String. Input : test_str = 'geeksforgeeks is best for geeks and best for CS', count_list = ['best', 'geeksforgeeks', 'computer'] Output : [2, 1, 0] Explanation : best has 2 occ., geeksforgeeks 1 and computer is not present in string.Input 4 min read Iterate over words of a String in Python In this article, weâll explore different ways to iterate over the words in a string using Python.Let's start with an example to iterate over words in a Python string:Pythons = "Learning Python is fun" for word in s.split(): print(word)OutputLearning Python is fun Explanation: Split the string into w 2 min read Python - Maximum Scoring word Given a String, the task is to write a Python program to compute maximum scoring words i.e words made of characters with a maximum positional summation. Examples: Input : test_str = 'geeks must use geeksforgeeks for cs knowledge'Output : geeksforgeeksExplanation : Sum of characters positional values 5 min read Python - Print the last word in a sentence Printing the last word in a sentence involves extracting the final word , often done by splitting the sentence into words or traversing the string from the end.Using split() methodsplit() method divides the string into words using spaces, making it easy to access the last word by retrieving the last 3 min read Python | Extract words from given string In Python, we sometimes come through situations where we require to get all the words present in the string, this can be a tedious task done using the native method. Hence having shorthand to perform this task is always useful. Additionally, this article also includes the cases in which punctuation 4 min read How to Append to String in Python ? In Python, Strings are immutable datatypes. So, appending to a string is nothing but string concatenation which means adding a string at the end of another string.Let us explore how we can append to a String with a simple example in Python.Pythons = "Geeks" + "ForGeeks" print(s)OutputGeeksForGeeks N 2 min read Find Length of String in Python In this article, we will learn how to find length of a string. Using the built-in function len() is the most efficient method. It returns the number of items in a container. Pythona = "geeks" print(len(a)) Output5 Using for loop and 'in' operatorA string can be iterated over, directly in a for loop. 2 min read Like