Python String Replace

python-string-replace-ipcisco.com

Python String Replace is one of the most used string functions in Python. With the help of this python replace() method, we can change any string with another string. Especially in some search and replace algorithms, Replace method is very useful. Here, we will focus on replace() method.

 

There are three paremeters of python replace() method. These are:

 

  • Old Value
  • New Value
  • Count

 

Old value is the string that will be changed. New value is the new string that will be replaced with old value. And the count is the number of this change. Here, the first two one is mandatory and the count parameter is optional parameter.

 


You can also learn all the other methods of Pythonstrings


 

Let’s see the below example. In this example, we will use “Paris” as old parameter and “Istanbul” as new parameter. We will not use the third count parameter here.

 

msg = "I would like to be in Paris. Because Paris has perfect historical places."
newmsg = msg.replace("Paris", "Istanbul")
print(newmsg)

 

The output of this Python String Replace example will be like below:

 

I would like to be in Istanbul. Because Istanbul has perfect historical places.

 

python-string-replace-2-ipcisco.com

 

 

Now, let’s do another example, with which we will also use count paremeter of string replace function. Here, we will change two word with three but only for two times.

 

msg = "I have two children, two dogs, two cats."
newmsg = msg.replace("two", "three", 2)
print(newmsg)

 

So, the output of this Python Replace code will be like below:

 

I have three children, three dogs, two cats.

 

python-string-replace-ipcisco.com

 

As you can see here, only the first two words are changed as three. And the last one is remaining.

 

In this lesson, we have learned Python String Replace method. This function is lone of the wideley used functions in python. You can use this function in any of your codes for variety of purposes. Especially for correcting something, replace function is widely used.

 

 

Back to: Python Programming Course > Python Strings

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Programming Course

Collapse
Expand