How to Replace the Kth word in a String using Python?


Strings are important data types in Python. Strings can be defined as the sequence of characters. Replacing the kth word in a String is an operation in which we want to replace the word which appears kth times in a String. In this article we will follow several methods to achieve it. We would look into the brute force method like using the loop statement, modules and libraries like re etc.

Using Loop and split Method

Loops are very common statements in most of the modern programming languages. We can either use the for or while loop to iterate over the iterable objects in Python. The enumerate method on the other hand is an in−built method in Python which returns an enumerated object. The object contains a pair of index and values of the iterable objects. To replace the kth word in String we can follow the following algorithm:

  • First split the String into words.

  • Iterate over the iterable object using the loop.

  • Find the kth word and replace it with the desired word.

Example

In the following code we used the split method to split the String into words. Next we have used the enumerate method of Python to iterate over it and for each iteration we keep finding if the word is kth word. If it is the kth word of the sequence we have appended the word to an initialized list which we later converted into a String data type using the join method.

def replace_kth_word(string, k, new_word):
    words = string.split()
    updated_words = []
    for i, word in enumerate(words):
        if i + 1 == k:
            updated_words.append(new_word)
        else:
            updated_words.append(word)
    updated_string = ' '.join(updated_words)
    return updated_string
test_string = "Apple is red"
k_value = 3
new_word_value = "sweet"
updated_string = replace_kth_word(test_string, k_value, new_word_value)
print("The original string is: " + test_string)
print("The updated string is: " + updated_string)

Output

The original string is: Apple is red
The updated string is: Apple is sweet

Using Split Method And Indexing

The split is an in−built method of Python which allows us to split a Python String based on a delimiter. It proves to be very handy when we try to retrieve important information from the Python String.

Syntax

string.split(delimiter)

The 'string' here is the name of the String object on which we want to perform the split operation. The delimiter on the other hand is the sequence with respect to which we need to split the String.

Example

In the following example we have splitted the String into words using the 'split' method. Next we have checked if the value of k is less than or equal to the length of the list. If it is True then we have replaced the word at the index with our desired word.

def replace_kth_word(string, k, new_word):
    words = string.split()
    if k <= len(words):
        words[k - 1] = new_word
    return ' '.join(words)
sentence = "Hello I will replace dog with cat"
k = 7
new_word = "lion"
updated_sentence = replace_kth_word(sentence, k, new_word)
print(f"The original String is: {sentence}")
print(f"The updated String is: {updated_sentence}")

Output

The original String is: Hello I will replace dog with cat
The updated String is: Hello I will replace dog with lion

Using Regular expression

Regular expression was originally designed to deal with the NLP problems. The regular expressions are the means to find important patterns and features in a String. It uses the wildcard pattern to determine the features. In Python we have separate library called 're'. The library is useful in a variety of fields like machine learning, text parsing, text preprocessing etc.

Example

In the following example we have used the 're' library. We defined the pattern in the 'pattern' variable. Next we used the 'findall' method of the 're' library to find the pattern in our given String. Next we used the lambda function to pop off the element at the kth index and replace it with our desired String.

import re

def replace_kth_word_regex(string, k, new_word):
    pattern = r'\b(\w+)\b'
    words = re.findall(pattern, string)
    if k < len(words):
        words[k - 1] = new_word
    return re.sub(pattern, lambda m: words.pop(0), string)
sentence = "Apple is my favourite fruit"
k = 1
new_word = "Orange"
updated_sentence = replace_kth_word_regex(sentence, k, new_word)
print(f"The original String is: {sentence}")
print(f"The updated String is: {updated_sentence}")

Output

The original String is: Apple is my favourite fruit
The updated String is: Orange is my favourite fruit

Using List Comprehension

List comprehension is a compact and elegant way of combining multiple expressions, statements etc. into a single expression to produce the elements of a list. The advantage of using this method is that we can combine multiple statements in one line and we can take advantage of other methods like lambda, and map functions.

Example

In the following example we have first split the String into a list of words using the 'split' method. Next we have used the list comprehension where we checked if the index of the word in the list is equal to k, if it is so we have replaced this with the desired word. Finally we have used the 'join' method to create String out of the list.

def replace_kth_word_generator(string, k, new_word):
    words = string.split()
    updated_words = [new_word if i == k else word for i, word in enumerate(words)]
    return ' '.join(updated_words)

sentence = "He has a house in London"
k = 3
new_word = "flat"
updated_sentence = replace_kth_word_generator(sentence, k, new_word)
print(f"The original String is: {sentence}")
print(f"The updated String is: {updated_sentence}")

Output

The original String is: He has a house in London
The updated String is: He has a flat in London

Use Only Join and Indexing Method

‘join’ is an in−built method in Python which we can use to combine multiple Strings. It takes any iterable object as the parameter and it concatenates the elements of the iterable object. Indexing on the other hand is a popular way of accessing the position of the elements in an iterable object. It is defined as the distance of any element from the first element of the iterable object.

Example

In the following example we have used the join method and indexing to replace the kth word. We have first split the String into a list using the split method of Python. Next we used the jon method to append the element up to kth index, new word and the elements after the kth elements to an empty String.

def replace_kth_word_regex_sub(string, k, new_word):
    temp = string.split(' ')
    updated_sentence = " ".join(temp[: k]  + [new_word] + temp[k + 1 :])
    return updated_sentence

sentence = "He has a house in London"
k = 3
new_word = "flat"
updated_sentence = replace_kth_word_regex_sub(sentence, k, new_word)

print(f"The original String is: {sentence}")
print(f"The updated String is: {updated_sentence}")

Output

The original String is: He has a house in London
The updated String is: He has a flat in London

Conclusion

In this article we understood how to replace the kth word in a String using Python. We can adopt the brute force method like using the loop statements, split etc. We can directly access the word using the split method and by using the indexing property. Libraries like ‘re’ allow us to perform the same in a different approach where we replace it through regular expressions instead of indexing.

Updated on: 18-Jul-2023

100 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements