Python Program to replace characters in a string

In this simple python program, we need to replace a character in a string. It is a number-based python program.

For a better understanding of this example, we always recommend you to learn the basic topics of Python programming listed below:

How to replace a string in python?

In this simple python program, we replace a character 'a' or 'A' with '$' within a string. It is a basic string program that is very easy to achieve in python programming. For example, let us take a string " cartoon" after running our python program, the output will be c$rtoon.

Let us check the implementation logic used in the python program; after accepting the string from the user, we are using a string replace function to achieve the desired output that will replace all the a or A with $. Finally, we print the output using the print statement in python.

What is the string replace function?

String replace(): it is a built-in function used in the python programming language, which has two parameters where we give the string to be replaced and the replacing string. Then the string replace function gives the output with all the string's occurrence is replaced by another substring. String replace has an optional parameter, too, which is the count. Which is used to replace a specific number of times the string has to replace.

ALGORITHM

STEP 1: Accept the string using the input method in python programming.

STEP 2: Use the string replace function to replace all the lower case a to $.

STEP 3: Use again the string replace function to replace all the upper case A to $.

STEP 4: Using print in python, print the replaced string.

Python Source Code

                                          string=input("Enter string:")

string=string.replace('a','$')

string=string.replace('A','$')

print("Modified string:")

print(string)
                                      

OUTPUT

Enter string: Have a nice day

Modified string: H$ve $ nice d$y