











Python Program to Replace a Particular Word by Another Word from a given String
Replace a Particular Word with Another Word in Python
Here on this page, we will learn to create a Python Program to Replace a Particular Word with Another Word.
Example :
Input : s = “Let’s Learn Python from Internet”, s1 = “Internet”, s2 = “PrepInsta”
Output : “Let’s Learn Python from PrepInsta”


Method Discussed :
- Method 1: Brute force approach
- Method 2: In-place Replacing
Method 1
Algorithm
- Initialize variable ans which will store empty string, c with -1 value
- Iterate using i till the length of list s
- For each iteration check if i< c. If the condition is true move to the next iteration else move to the else part.
- If the above condition is false Initialize k to zero. Check the condition if s[i] is equal to s1[k] and i+len(s1) is less than or equal to length of s. If true then initialize z to zero.
- Use nested for loop using the j variable from i to length of s +1. For each iteration initialize z to j. Check the condition if s[j] is not equal to s1[k]. If true we will come out of this loop else we will increase k by 1.
- If z is equal to i+length(s1)-1 then append s2 at the end of ans variable. Assign c value of i+len(s1). Else append s at the end of ans variable
- Else append s[i] at the end of ans variable
- Return ans variable.
Python Code
Run
def modifyString(s, s1, s2): ans = "" c = -1 for i in range(len(s)): if i < c: continue k = 0 if s[i] == s1[k] and i + len(s1) <= len(s): z = 0 for j in range(i, i + len(s1)): z = j if s[j] != s1[k]: break else: k += 1 if z == i + len(s1) - 1: ans += s2 c = i + len(s1) else: ans += s[i] else: ans += s[i] return ans s = "Let's Learn Python from Internet" s1 = "Internet" s2 = "PrepInsta" print("Original String :", s) print("Modified String :", modifyString(s, s1, s2))
Output:
Original String : Let's Learn Python from Internet
Modified String : Let's Learn Python from PrepInsta
Method 2:
In-Built Function
As you know Python is one of the most simple programming languages. Python has an In-Built Function “replace” for strings. For which we don’t even require any additional libraries. Let’s see how to use it:
Replace Function Format :- a.replace(b, c)
Condition
To use replace function a, b, c should be in string format only.
- a – Sentence in which you want to replace the word
- b – Word you want to replace from a
- c – Word which is supposed to replace b
Python Code
Run
s = "Let's Learn Python from Internet" s1 = "Internet" s2 = "PrepInsta" x = s.replace(s1, s2) print("Original String :", s) print("Modified String :", x)
Output:
Original String : Let's Learn Python from Internet
Modified String : Let's Learn Python from PrepInsta
For similar Questions click on the given button.
Login/Signup to comment