Python Program to Replace all Occurrences of ‘a’ with $ in a String
Given a string, the task is to write a Python program to replace all occurrence of ‘a’ with $.
Input: Ali has all aces Output: $li h$s $ll $ces Input: All Exams are over Output: $ll Ex$ms $re Over
The first approach uses splitting of the given specified string into a set of characters. An empty string variable is used to store modified string . We loop over the character array and check if the character at this index is equivalent to ‘a’ , and then append ‘$’ sign, in case the condition is satisfied. Otherwise, the original character is copied into the new string.
Modified string : $md$ni $th$ni kh$rch$ rup$iy$.
The second approach uses the inbuilt method replace() to replace all the occurrences of a particular character in the string with the new specified character. The method has the following syntax :
replace( oldchar , newchar)
This method doesn’t change the original string, and the result has to be explicitly stored in the String variable.
Modified string : $n $pple $ d$y keeps doctor $w$y.
The time and space complexity for all the methods are the same:
Time Complexity: O(n)
Space Complexity: O(n)