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.

Example
# string is immutable
s = "Hello"
s[0] = "h" # ❌ error
TypeError: 'str' object does not support item assignment

However, there are ways to change a character in a string. We will look at them in this guide.

    Table of Contents

  1. Using replace() Method
    1. Example 1
    2. Example 2
  2. Custom Function to Replace Characters in String
  3. Conclusion

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.

Syntax:

string.replace(old, new, count)

Where:

Let's look at some examples.

Example 1:

Replace all occurrences of 't' with 'T' in the string.

Example
str = "tutorialstonight is best place to learn python"
str = str.replace("t", "T")
print(str)
TuTorialsTonighT is besT place To learn pyThon

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.


Example 2:

Replace only the first 2 occurrences of 't' with 'T' in the string.

For this, you have to use 3rd optional argument count.

Example
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)
TuTorialstonight is best place to learn python

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.

Example
# 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"))
TuTorialstonight is best place to learn python
TuTorialsTonighT is besT place To learn pyThon

Let's understand the code.

  1. First, we define a function replace_string() with 4 arguments.
  2. 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.
  3. 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.
  4. Then we decrement the count by 1. If the count is 0, we break the loop and return the string.

Conclusion

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.