Python Questions Write a function which is passed 3 paramete
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\')
Solution
Function \"replace\" implementation without using an in-built library. The following function uses recursion to replace all the occurrences of a character (old_c) by a new character (new_c) in a given string (s).
Slicing [:] is used to implement operation on the string. A slicing is a substring of string. For example,
s[1:] means cut the first character of string \"s\" and the resultant substring would be a string with rest of the characters.
--------------------------------------------------------------------------------------
PYTHON CODE:
# function replace takes three parameters
# a) string: original string
# b) old_c: character to be replaced
# c) new_c: new character
def replace(s, old_c, new_c):
if s==\'\':
return \'\'; # end condition for recursion
# call replace recursively using python slicing
if s[0]==old_c:
return new_c + replace(s[1:], old_c , new_c);
return s[0] + replace(s[1:], old_c , new_c);
# original string
s=\'science\';
old_c=\'c\'; # All occurances of old_c to be replaced
new_c=\'t\'; # All old_c to be replaced by new_c
# Call replace function
new_str=replace(s, old_c, new_c);
# print the new string
print(\'Original string: \'+ s);
print(\'New string: \'+ new_str);
--------------------------------------------------------------------------------------
OUTPUT:
Original string: science
New string: stiente
