Python Questions: Write a function which is passed 3 parameters, all of which ar
ID: 3795484 • Letter: P
Question
Python Questions:
Write a function which is passed 3 parameters, all of which are strings. The function returns a copy of the string s with all occurrences of old_c replaced by new_c. You are not allowed to use the built-in Python replace method. You may assume that old_c and new_c are both strings of length 1.
The solution must be recursive
For example:
>>> replace('science', 'c', 't')
'stiente'
>>> replace('python', 's', 't')
'python'
>>> replace('rocker', 'r', 'd')
'docked'
Explanation / Answer
def replace(word,char1,char2):
string = list(word)
result = []
for i in string:
if i == char1:
i = char2
result.append(i)
print ''.join(result)
replace('science','c','t')
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.