I am trying to write a user defined function to replace all occurances of a substring in a string with another without using the replace() function in python. find_sub() is a user-defined function that returns the starting index of the substring you are looking for. I have tried the following code but it is not terminating.
def replace_sub(original_str, old_sub, new_sub):
if find_sub(original_str, old_sub) == -1:
print("Cannot replace this!")
return -1
else:
substrings = []
initial_pos = 0
final_pos = find_sub(original_str, old_sub)
while True:
if final_pos == -1:
part = original_str[initial_pos:]
substrings.append(part)
break
part = original_str[initial_pos:final_pos]
substrings.append(part)
initial_pos = final_pos + len(old_sub)
final_pos = find_sub(original_str[initial_pos:], old_sub)
replaced_str = ""
for part in substrings:
replaced_str = part + new_sub
return replaced_str
find_sub?