Python String replace
Now, we are going to learn about the replacement method. As the name of the method says, the replace method helps in replacing the old string with the new string in the given string. Let’s have a look at a simple example, through which, we can understand the replacement method.
As you can see in the above program, we have a string, which says that ‘Kiwi is my favorite fruit.’. Then, in the next line, we are trying to replace the string Kiwi, with the string Apple in the str1, using the replace method. Doing this will replace every occurrence of Kiwi with Apple. Note that the replace method returns a new string, with the effective changes. After that, we are trying to print the str2, which is the new string with effective changes.
Python String replace() Method
Let’s try to have a look at the output –
Apple is my favorite fruit.
As you can see in the output, we have got the string Kiwi replaced with Apple. Since we had only one occurrence of Kiwi, the replacement was done only once, but it replaces all the occurrences of the specified string with the new string, if the third argument is not specified, which is a count. So, Let’s try to have the third argument as well.
As you can see in the above program, we have a string, which has Kiwi 6 times, and then we are using the replace method on the string, to replace the string Kiwi, with the string Apple. But this time, we are doing this only three times, as specified in the third argument.
Now, Let’s have a look at the output –
Apple Apple Apple Kiwi Kiwi Kiwi
As you can see, the string Kiwi was replaced by the string Apple, three times only. So, we can make use of the replace method, as and when required. Using the replace method replaces all/specified number of occurrences of some string, with another string. Remember that this method returns the string with effective changes, and the original string is unchanged.
So, this was about the replace method, and we can use the method for strings, as and when required. Remember that the replace method replaces all / specified occurrences of some old string, with the new string. Also, the new string is returned from the replace method.