Using Python to replace characters in a string

In this short tutorial, we look at how you could use Python to replace a character in a string. We break down the code to help you understand the function.

Table of Contents: Python replace character in string

  • Python replace()
  • Code and Explanation
  • Closing thoughts - Python replace character in string

Unlike lists, Python strings are immutable and hence they cannot be changed once initialized. Because of this, methods used to edit lists cannot be used on a string. However, Python has a few functions that can replace characters in strings.

Python replace():

The Python replace() method is used to find and replace characters in a string. It requires a substring to be passed as an argument; the function finds and replaces it. The replace() method is commonly used in data cleaning.

However, given strings are immutable, the function replaces characters on a copy of the original string. So ensure you save the new string in case you intend to further use it.

Syntax of replace():

string.replace(old, new, count)
Here “string” refers to the string you are looking to replace characters with.

Parameter (Python replace character in string):

  • Old - Required, the substring you are looking to replace.
  • New - Required, the substring you are looking to replace the old string with.
  • Count - Optional, specifies the number of times you want the string to be replaced. If left empty, all occurrences will be replaced.

Code and Explanation:

# use of replace() method 
 
string = "Join our community of top freelancers"
  
# replace "top" with "top 1%"
print(string.replace("top", "top 1%"))
 
# printing the original string
print(string)
The above code snippet outputs the following:
Join our community of top 1% freelancers
Join our community of top freelancers

As you can see the substring was replaced but the original string still remains the same. Also, given we did not specify a count argument, all the occurrences were replaced.

Let us look at a case where we replace multiple instances of a string.

string = "python is a programming language"

# replace "p" with "P" once
print(string.replace("p", "P",1))
 
# replace "p" with "P" once
print(string.replace("p", "P"))

In the above code snippet, we have first replaced “p” only once whereas in the second print statement we have not passed a counter-argument. This means all the occurrences would be replaced.

The output is as follows:
Python is a programming language
Python is a Programming language

Closing thoughts - Python replace character in string:

There are other methods that can be used apart from the replace method to replace characters in strings. However, these methods would involve typecasting or slicing, and concatenation. Although these methods work, they are not preferred over the replace() method. However, I would recommend you give them a read and understand the concept.