Python String – replace ( ) Method is a very powerful tool if used correctly. The right use of the same could save you a huge amount of time. For example, let’s say you are working on a project and one of your team members misspelt a name repeatedly in the entire project. Now you have to correct it. In order to do that you have two options.
- Sit back find all the incorrect names and replace them with the correct one manually, or
- Let the computer do all the hard work.
So, which one do you think will be the most efficient way to carry out this work? If I have to choose, then I will go with the second option. Moreover, in this tutorial, I will show you how to properly use Python String – replace ( ) Method.
[bctt tweet=”Python String – replace ( ) Method is a very powerful tool if used correctly. ” username=”RebellionRider”]
What Is The Python String replace ( ) Method?
As the name suggests, String Method replace ( ) is a built-in string method which replaces one pattern from another and returns a new string as a result.
Consequently, you must be wondering why it returns a new string I will explain to you that at the end of this tutorial.
The Syntax of Python String – replace ( ) Method.
It is always recommended to get familiar with the syntax of a function/method before you start using it therefor here we are –
replace (old_str, new_str, instance)
old_str – The first argument is the old string. This is the string which you want to replace. Therefore, it could be a single character or a multi-character string.
new_str – The second argument is a new string. This is the string that will replace the old one.
instance – This argument indicates, number of instances of old string which will get replaced by the new one. In addition, among three this is the only integer argument.
Among all the arguments only instance is the one that is optional, rest of them are mandatory. Consequently, if you do not specify the last argument (instance), then by default all the instances of the old string in the base string will get replaced by the new one.
Examples of Python String – replace ( ) Method
In order to perform an example, we first need a base string over which we will run our string method replace. Thus, for today’s demonstration, our base string will be. –
I love Pizza. Pizza is my guilty pleasure. I believe Pizza doesn’t have calories. Pizza should be declared as king of foods.
As you can see, here we are using a multi-line string for the demonstration. Therefore, I suggest you to check the tutorial on multi-line strings in Python first.
Moreover, now that we have our base string, let’s do our first example-
Example 1: Python String – replace ( ) without the optional parameter.
In the first example, I will only use the first two parameters of the method. Meanwhile, I will save the third parameter for the next example.
Now say, you were a big fan of pizza when you wrote this message. Afterward, you realized that “fudge cake” is much better than a pizza. Consequently, you decided to modify this message. Let’s see how we can do this using string method replace —
base_str = “““I love Pizza. Pizza is my guilty pleasure. I believe Pizza doesn’t have calories. Pizza should be declared as king of foods.””” result =base_str.replace('Pizza', 'Fudge Cake') print(result)
Another way to write the above code will be
base_str = “““I love Pizza. Pizza is my guilty pleasure. I believe Pizza doesn’t have calories. Pizza should be declared as king of foods.””” Print(base_str.replace('Pizza', 'Fudge Cake'))
Here except from the way of calling the Python String – replace ( ) method, everything is pretty much the same therefore both codes will produce the same result.
[bctt tweet=”Learn the concepts of Python String – replace ( ) method with the Multi-line String. ” username=”RebellionRider”]
Example 2: Python String – replace ( ) with optional parameter.
In this example we will use all three parameters of the string method replace ( ). Firstly, let’s understand what is the significance of this optional parameter instance?
The third parameter instance let’s you control the number of old string instance to be replaced by the new string. For example, let’s say your team member wrongly typed the name for a total of 18 times. After analyzing the project, you realized that only the first 16 entries are incorrect.
In such use-cases, where only the first few entries needs to be replaced and not all, you use the third parameter instance of Python string method replace ( ).
Now once again let’s take the example of our base string. Let’s say, you only want to modify the first three instances of “Pizza” with “Fudge Cake”.
Therefore we simply have to add 3 as the value of our third parameter in the method call. Like this –
base_str = “““I love Pizza. Pizza is my guilty pleasure. I believe Pizza doesn’t have calories. Pizza should be declared as king of foods.””” result =base_str.replace('Pizza', 'Fudge Cake', 3) print(result)
Subsequently, you could see that except from adding integer 3 in the method call we changed nothing. Accordingly, on execution, only the first three instances of “Pizza” will get replaced with “Fudge Cake”, not all.
So, that is how we properly use a Python String replace ( ) method.
Now let’s discuss something which everyone knows but nobody shares. Why string Method replace ( ) returns a new string. This secret could help you with your interview and save you from various errors.
Python String – replace ( ) returns a new string.
In the meantime, if you learn faster through videos then you can watch this explanation here in my video. But, those who love reading, here you go –
If you remember, earlier I said that the replace ( ) method, returns a new string as a result. The question here is Why a new string? You will get the answer to this question in the explanation of how the method call works.
Knowing how to use/call a function may be easy but understanding what happens in the background will give you an inside edge.
[bctt tweet=”Learning how to call a method is easy but learning how the method call works is worth the penny ” username=”RebellionRIder”]
When you call string method replace ( ). It takes the base string then it creates a copy of it. While creating that new copy the interpreter substitutes the old string with the new string that you have specified during the method call. Once the process of replacing the old string with the new one is done then Python interpreter shows that modified copy of the base string as the output to the user.
In this whole process the original base string remains the same. It is because in Python in-built objects like strings are immutable. Which means once they are created they cannot be changed. In particular, they will remain the same as they were created. Moreover, any attempt to change will result in an error.
That is how and why string method replace ( ) returns a new string as a result.
Good Luck and God Speed!