Replace instances of a character in a String in Python

In this Python tutorial, we will learn about methods through which we can replace instances of a character in a string using Python Programming language.

Table Of Contents

Method 1 : Using for loop:

First technique that we will be using to replace the instances of a character in a string is the for-loop. We will create an empty string first. Then we will loop through all characters of string using a for loop and add them to the empty string, except for some specific characters. During iteration we will check for specific characters and instead of adding them we will add the repacement character in the new string.

In this method we will also be using the range() and len() functions. The range() function returns the sequence of numbers from 0 till the given number. Whereas, the len() function returns the length of the sequence provided. We will be using range() to start the iteration of the string and len() will return the length of the string, which will be used to stop the iteration.

Let’s see an example, where we will replace all occurrences of character ‘a’ with ‘A’.

# initialize a string
example_str = "Python Programming language"

# initialize an empty string
new_str = ''

# looping through all characters of string by index
for i in range(0, len(example_str)):
    if(example_str[i] == 'a'):
        new_str += 'A'
    else:
        # this is to add rest of the chars in the new variable.
        new_str += example_str[i]

print(new_str)

OUTPUT :

Python ProgrAmming lAnguAge

In the above example, by using a for loop we have successfully replaced all occurrences of char ‘a’ with the ‘A’ in string example_str.

Method 2 : Using replace() method

Next method that we will be using to replace instances of a character in a string is the replace() method of class str. It takes two arguments,

  • old value : value which needs to be replaced.
  • new value : value with which the old value will be replaced.

It returns a string with the formatted string value. Basically it replaces all the instances of given char with the new char in a copy of string and returns that. See the example code below,

# initialized a string
example_str = "Python Programming language"

# replacing 'a' with 'A' using the replace() method
example_str = example_str.replace('a', 'A')

print(example_str)

OUTPUT :

Python ProgrAmming lAnguAge

So in the above example, we have replaced all the instances of char ‘a’ with char ‘A’ using the str.replace() method.

Method 3 : Using re.sub()

Another method that we can use to repalce the instances of a character in a string is the sub() function of re module in Python. The re stands for Regular Expression, which comes bundled with Python Programming language and mainly used for pattern matching. The sub() method recieves five arguments,

  • pattern : A pattern which needs to be matched, can also be a pattern object.
  • repl : The replacemet of the pattern found.
  • string : The input string, in which substrings will be replaced based on regex pattern.
  • count : It specifies the maximum or minimum number of repalcement. If 0 then completely skips. If not provided replaces every instance. It is an Optional argument.
  • flags : This modifies the standard behaviour. Optional

SYNTAX:

re.sub(pattern, repl, string, count, flags)

It looks for all the substrings in string that matches the given regex pattern and replaces those substrings with a replacement string i.e. repl.

Let’s see an example, where we will replace all occurrences of character ‘a’ with ‘A’.

import re

# initialized a string
example_str = "Python Programming language"

# replacing all the instances of 'a' with 'A' using sub() function
new_str = re.sub('a', 'A', example_str)

print(new_str)

OUTPUT :

Python ProgrAmming lAnguAge

In the above code example by using the re.sub() function, we have succesfully replaced all the instances of char ‘a’ in the variable example_str with char ‘A’ and stored it in new_str variable.

Summary

So in this Python tutorial, we learned about three different method through which we can replace all the instances of a given character in a string with a new one. All the methods can be useful but the method with the most easiest Syntax and most easy to understand is the repalce method, simply provide the old value and new value and the job is done.

Also we have used Python 3.9.12 for writing example codes. Type python –version to check your python version. Always try to write example codes on your machine. Happy Coding.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top