Python Program to Replace all Occurrences of ‘a’ with $ in a String

PythonServer Side ProgrammingProgramming

When it is required to replace all the occurrences of ‘a’ with a character such as ‘$’ in a string, the string can be iterated over and can be replaced using the ‘+=’ operator.

Below is a demonstration of the same −


 Live Demo

my_str = "Jane Will Rob Harry Fanch Dave Nancy"

changed_str = ''

for char in range(0, len(my_str)):
   if(my_str[char] == 'a'):
      changed_str += '$'
      changed_str += my_str[char]
print("The original string is :")
print("The modified string is : ")


The original string is :
Jane Will Rob Harry Fanch Dave Nancy
The modified string is :
J$ne Will Rob H$rry F$nch D$ve N$ncy


  • A string is defined and is displayed on the console.

  • An empty string is also defined.

  • The string is iterated, and if the alphabet ‘a’ is encountered, it is replaced with ‘$’.

  • Otherwise, it is not changed.

  • The resultant output is displayed on the console.

Published on 14-Apr-2021 15:54:27