Python Replace Character in String
In this short guide, you will learn how to replace a character in a string in Python. We will look at different programs with their explanation.
Strings are immutable in Python. This means that once a string is created, it cannot be changed.
If you simply access a character in the string and try to change it, you will get an error.
For example, the following code will give an error.
# string is immutable s = "Hello" s = "h" # ❌ error
However, there are ways to change a character in a string. We will look at them in this guide.
- Using replace() Method
- Example 1
- Example 2
- Custom Function to Replace Characters in String
Table of Contents
Using Python replace() method
The replace() method is a built-in method in Python. It is used to replace a part of a string with another string.
The method returns a new string where the occurrences of the old substring are replaced with the new substring.
string.replace(old, new, count)
- old is the substring to be replaced
- new is the substring to replace the old substring
- count (optional) is the number of times the old substring is to be replaced. If not specified, all occurrences of the old substring are replaced.
Let's look at some examples.
Replace all occurrences of 't' with 'T' in the string.
str = "tutorialstonight is best place to learn python" str = str.replace("t", "T") print(str)
In this above example, you can see that all occurrences of 't' in the string are replaced with 'T'.
🤔 If Python string is immutable, how does the replace() method work?
The replace() method does not change the original string. It returns a new string with the replaced characters.
So you have to assign the new string to the original string variable. The original string is always the same.
Replace only the first 2 occurrences of 't' with 'T' in the string.
For this, you have to use 3rd optional argument count.
str = "tutorialstonight is best place to learn python" # replace only the first 2 occurrences of 't' with 'T' str = str.replace("t", "T", 2) print(str)
The output of the above example shows that only the first 2 occurrences of 't' in the string are replaced with 'T'.
Custom Function to Replace Characters in String
Let's create your own function to replace a character in a string.
Our function will take 4 arguments, the string, the character to be replaced, the character to replace with, and the number of characters to be replaced.
Let's look at the code.
# replace string custom function def replace_string(str, old, new, count=-1): # if count is -1, replace all occurrences if(count == -1): count = str.count(old) # loop through the string for i in range(len(str)): # if character matches with old character if str[i:i+len(old)] == old: # replace the character str = str[:i] + new + str[i+len(old):] count -= 1 # if count is 0, return the string if count == 0: break return str str = "tutorialstonight is best place to learn python" # replace only the first 2 occurrences of 't' with 'T' print(replace_string(str, "t", "T", 2)) # replace all occurrence of 't' with 'T' print(replace_string(str, "t", "T"))
Let's understand the code.
- First, we define a function replace_string() with 4 arguments.
- Then we check if the count is -1 (default value when no count is passed). If yes, we set the count to the number of occurrences of the old character in the string. So that all occurrences of the old character are replaced.
- Then we loop through the string and check if the character matches with the old character. If yes, we replace the character with the new character.
- Then we decrement the count by 1. If the count is 0, we break the loop and return the string.
This is the end of this tutorial. Here we have learned how to replace a character in a string in Python.
We have replaces characters with and without using the replace() method. Also, we have created our own function to replace characters in a string.