In this article we will discuss how to replace single or multiple characters in a string in Python.

Python provides a str.replace() function i.e.

It returns a new string object that is a copy of existing string with replaced content. Also,

  • If count is not provides then it will return a string with all the occurrences of ‘old’, replaced with ‘new’ string.
  • If count parameter is passed then it will return a string with first ‘count’ occurrences of ‘old’ string replaced with ‘new’ string.

Let’s understand by examples,

Replace all occurrences of given character / string in a string

Suppose we have a string i.e.

Now, lets replace all the occurrences of ‘s’ with ‘X’ i.e.

Contents of otherStr is as follows,

As strings are immutable in Python, so we can not change its content. Therefore member functions like replace() returns a new string.
As we have not provided the count parameter in replace() function. So, it will replace all the occurrences of ‘s’ with ‘X’. But what if we want to replace only first few occurrences instead of all? Let’s see how to do that,

Replace first n occurrences of given character / sub string in a string

Suppose we have a string i.e.

Now, lets replace first 2 occurrences of ‘s’ with ‘XXXS’ i.e.

Contents of otherStr is as follows,

As we have passed the count parameter as 2, so only first 2 occurrences of ‘s’ will be replaced in the returned copy.

Replace multiple characters/strings in a string

str.replace() function can replace the occurrences of one given sub string only. But what if we want to replace multiple sub strings in a given string ?

Suppose we have a string i.e.

Now, how to replace all the occurrences of these three characters ‘s’, ‘l’, ‘a’ with this string ‘AA’ ?
Let’s create a new function over replace() to do that i.e.

It will replace all the occurrences of strings in List toBeReplaces with newString in the main given list mainString.
Let’s see how to replace the occurrences of [‘s’, ‘l’, ‘a’] with “AA” i.e.

Contents of otherStr is as follows,

Complete example is as follows,

Output:

 

 

Click Here to Subscribe for more Articles / Tutorials like this.