string replace() in Python

In this article, we would cover string replace() method in Python. Herein, it would first search the substring and if found, will be replaced with its replacement substring. The following is its syntax

str.replace(old, new[, count])

where,

old – the substring we want to search and replace,

new – the new substring we want to have in place of old substring,

count – the number of occurrences we would like to replace. It is an optional parameter. If we don’t provide any value here then, it will search and replace for all occurrences as default.

Furthermore, we have to necessarily provide old and new parameter values.

string replace() in Python

Let’s understand replace() method with couple of examples.

Example I. We have a string, x

x="Hello, how are you? How have you been?"

And, we want to search for substring “how” and replace it with “$“.

outcome=x.replace("how","$")

We store the result in variable outcome. And, to get the result we use print() method –

print(outcome)

It would return with –

Hello, $ are you? How have you been?

You would notice two things from here, since we didn’t provide the count value. Therefore, the replace() method went for all the occurrences. Despite, it chose to ignore “How“. Reason – it is case sensitive.

Example II. We modify the above string a bit. And, provide the count value.

x="Hello, how are you? how have you been? how are you?"

Here also, we would replace “how” with “$” but only for two occurrences i.e. count=2

outcome=x.replace("how","$",2)

We store the result in variable outcome. And, to get the result we use print() method –

print(outcome)

It would return with –

Hello, $ are you? $ have you been? how are you?

Since, we have used count=2. Therefore, only two occurrences of “how” are replaced with “$“.

In conclusion, we have discussed string replace() in Python.

Similar Posts