View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
Given a string, the task is to write a Python program to replace all occurrence of ‘a’ with $.
Examples:
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.
Python3
str
=
"Amdani athani kharcha rupaiya."
modified_str
=
''
for
char
in
range
[
0
,
len
[
str
]]:
if
[
str
[char]
=
=
'a'
]:
modified_str
+
=
'$'
else
:
modified_str
+
=
str
[char]
print
[
"Modified string : "
]
print
[modified_str]
Output:
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.
Python3
str
=
"An apple A day keeps doctor Away."
str
=
str
.replace[
'a'
,
'$'
]
print
[
"Modified string : "
]
print
[
str
]
Output:
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]
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
Sometimes, while working with Python strings, we can have a problem in which we need to replace all occurrences of a substring with other.
Input : test_str = “geeksforgeeks” s1 = “geeks” s2 = “abcd”
Output : test_str = “abcdforabcd” Explanation : We replace all occurrences of s1 with s2 in test_str.
Input : test_str = “geeksforgeeks” s1 = “for” s2 = “abcd”
Output : test_str = “geeksabcdgeeks”
Approach 1
We can use inbuilt function replace present in python3 to replace all occurrences of substring.
Implementation using the inbuilt function:-
Python3
input_string
=
"geeksforgeeks"
s1
=
"geeks"
s2
=
"abcd"
input_string
=
input_string.replace[s1, s2]
print
[input_string]
Approach 2:
Splitting the string by substring and then replacing with the new string.split[] function is used.
Python3
test_str
=
"geeksforgeeks"
s1
=
"geeks"
s2
=
"abcd"
s
=
test_str.split[s1]
new_str
=
""
for
i
in
s:
if
[i
=
=
""]:
new_str
+
=
s2
else
:
new_str
+
=
i
print
[new_str]
The Time and Space Complexity for all the methods are the same:
Time Complexity: O[n]
Auxiliary Space: O[n]