Python Program: Replace Occurrences of a Character

Meenakshi Agarwal
By
Meenakshi Agarwal
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large...
5 Min Read
Replace all or specified no. of occurrences of chars sub strings in Python

Problem: Replace All Occurrences of a Char in Python

This Python programming explains how to replace occurrences (single or all) of a character in a string. It tells the complete logic in detail.

Python provides many simple methods to replace a character in the target string. However, we will demonstrate it using the string replace() function. There are three use cases, we will cover in this short tutorial.

You must also check out this post – Python Replace String with Examples

String replace() syntax

This Python method has the following syntax:

# Python's String Replace Function

python_string.replace(old_str, new_str, count)

Parameters:

 old_str => Old string to be replaced
 new_str => New string used for substitution
 count => Replacement counter

Returns:

 Returns a copy of the old string with the new after replacment.

The above function creates a new string and returns the same. It contains a copy of the original value replaced with the new one.

You should note the following points while using the string.replace() method:

  • If the count parameter is not specified, all occurrences of the old string will be replaced with the new one.
  • If there is some value in the count parameter, the old string will be replaced a no. of time by the new one.

List of use cases

Let’s now do some hands-on with examples.

Replace all occurrences of a char/string in a string

Assume we have the following original string:

original_str = "Python Programming language is easy to learn and easy to code."

Your task is to replace all occurrences of the string “easy” with the following:

replace_str = "simple"

Here is the sample Python code to achieve this:

"""
Example:
 Replace all occurrences of the specifed string in the original string
"""
final_str = original_str.replace("easy" , replace_str) 
print(final_str)

The output is as follows:

Python Programming language is simple to learn and simple to code.

Let’s check out one more example that replaces a character with another one in the original string.

original_char = '.'
replace_char = '!'

The below code does the needful.

"""
Example:
 Replace all occurrences of a given char in the original string
"""
final_str = original_str.replace(original_char ,  replace_char) 
print(final_str)

The output is as follows:

Python Programming language is easy to learn and easy to code!

Replace num occurrences of a char/string in a string

Let’s do our test with the following original string:

original_str = "Python Programming language, Python Programmer, Python Unit Testing."

Your task is to replace the first two occurrences of the string “Python” with the following:

replace_str = "CSharp"

Here is the sample Python code to achieve this:

"""
Example:
 Replace first two occurrences of the specifed string in the original string
"""
final_str = original_str.replace("Python" , replace_str, 2) 
print(final_str)

The output is as follows:

CSharp Programming language, CSharp Programmer, Python Unit Testing.

Since we have supplied 2 as the count argument value, so it would only replace the first two occurrences of the “Python” string.

Related Topic – How to Remove Characters from a String in Python

How to replace multiple chars/substrings in a string

The function replace() only supports one string to get replaced. However, you might want to replace multiple chars or substrings in your target string.

For example, we may have the following original string:

orig_string = "JavaScript Programming language, CSharp Programmer, Python Unit Testing."

Now, you want to replace “JavaScript” with “Python” and “CSharp” with “Python”. To accomplish this, we have created a custom function.

"""
Function:
 Replace a list of many sub strings with a new one in original string.
"""
def replaceMany(orig_str, substring_list, new_str):
   # Traverse the substring list to replace
   for string in substring_list :
      # Test if string exists in the original string
      if string in orig_str :
         # Replace the string
         orig_str = orig_str.replace(string, new_str)
   return orig_str

Now, let’s invoke our custom function by passing the desired parameters.

final_str = replaceMany(orig_string, ["JavaScript", "CSharp"], "Python")
print(final_str)

The output will come as:

Python Programming language, Python Programmer, Python Unit Testing.

Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Twitter) if you gained some knowledge from this tutorial.

Enjoy coding,
TechBeamers.

Share This Article
Subscribe
Notify of
guest

0 Comments
Newest
Oldest
Inline Feedbacks
View all comments