Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Replace the Kth word in a String using Python?
Replacing the kth word in a string is a common string manipulation task in Python. This involves identifying the word at a specific position (k) and substituting it with a new word. Python offers several approaches using built-in methods like split(), list comprehension, and regular expressions.
Using Split Method and Indexing
The simplest approach uses split() to convert the string into a list of words, then directly accesses the kth word using indexing.
Syntax
string.split(delimiter)
The split() method divides a string based on a delimiter (space by default) and returns a list of words.
Example
def replace_kth_word(string, k, new_word):
words = string.split()
if 1 <= k <= len(words):
words[k - 1] = new_word
return ' '.join(words)
sentence = "Hello I will replace dog with cat"
k = 5
new_word = "lion"
updated_sentence = replace_kth_word(sentence, k, new_word)
print(f"Original string: {sentence}")
print(f"Updated string: {updated_sentence}")
Original string: Hello I will replace dog with cat Updated string: Hello I will replace lion with cat
Using List Comprehension
List comprehension provides a more concise way to replace the kth word by creating a new list with the replacement in a single line.
Example
def replace_kth_word_comprehension(string, k, new_word):
words = string.split()
updated_words = [new_word if i == k - 1 else word for i, word in enumerate(words)]
return ' '.join(updated_words)
sentence = "Apple is my favourite fruit"
k = 1
new_word = "Orange"
updated_sentence = replace_kth_word_comprehension(sentence, k, new_word)
print(f"Original string: {sentence}")
print(f"Updated string: {updated_sentence}")
Original string: Apple is my favourite fruit Updated string: Orange is my favourite fruit
Using Regular Expressions
The re module provides pattern-based word replacement using regular expressions, which is useful for complex text processing scenarios.
Example
import re
def replace_kth_word_regex(string, k, new_word):
pattern = r'\b(\w+)\b'
words = re.findall(pattern, string)
if 1 <= k <= len(words):
words[k - 1] = new_word
return re.sub(pattern, lambda m: words.pop(0), string)
sentence = "Python is a powerful language"
k = 3
new_word = "versatile"
updated_sentence = replace_kth_word_regex(sentence, k, new_word)
print(f"Original string: {sentence}")
print(f"Updated string: {updated_sentence}")
Original string: Python is a powerful language Updated string: Python is versatile powerful language
Using Slice and Join
This method combines list slicing with the join() method to reconstruct the string with the replacement word.
Example
def replace_kth_word_slice(string, k, new_word):
words = string.split()
if 1 <= k <= len(words):
updated_sentence = " ".join(words[:k-1] + [new_word] + words[k:])
return updated_sentence
return string
sentence = "He has a house in London"
k = 4
new_word = "flat"
updated_sentence = replace_kth_word_slice(sentence, k, new_word)
print(f"Original string: {sentence}")
print(f"Updated string: {updated_sentence}")
Original string: He has a house in London Updated string: He has a flat in London
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Split and Index | High | Fast | Simple replacements |
| List Comprehension | Medium | Fast | Functional programming style |
| Regular Expressions | Low | Slower | Complex pattern matching |
| Slice and Join | High | Fast | Immutable approach |
Conclusion
The split and indexing method is the most straightforward approach for replacing the kth word in a string. Use list comprehension for concise code or regular expressions when you need advanced pattern matching capabilities.
