replace( ) Function
The replace( ) Function is used to replace a substring with the new one.
x = "Hello Beautiful World" y = x.replace("Beautiful", "Wonderful") print(y)
In the above code, we have declared a String 'Hello Beautiful World' and assigned it to a variable 'x'.
And we would be replacing 'Beautiful' with 'Wonderful', from the String, 'Hello Beautiful World'.
So, we have used the 'replace( )' Function to replace 'Beautiful' with 'Wonderful'.
As we can see, there are two parameters in the 'replace("Beautiful", "Wonderful")' function.
And thus the substring 'Beautiful' is searched in the String, 'Hello Beautiful World'. When found, 'Beautiful' is replaced with 'Wonderful'.
And the new String becomes,
Now, let us say, we have the below String,
And you are just suppose to change the first substring 'Beautiful' with 'Wonderful'.
Something like the below,
To solve this, there is a third parameter used by 'replace()' function that says how many occurrence that needs to be replaced.
Let us see with the below example.
x = "The Beautiful world is Beautiful indeed" y = x.replace("Beautiful", "Wonderful", 1) print(y)
So, if you see the above output, only the first occurrence of 'Beautiful' is replaced with 'Wonderful'.
That is because of the below line,
Where we have specified the third parameter as '1'.
Which says that only replace 1 occurrence of the word 'Beautiful'.
And thus we got the output,
The Beautiful world is Beautiful indeed