0

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
2
  • 1
    what is find_sub ? Commented Nov 15, 2019 at 21:10
  • find_sub is a user-defined function that does the same thing as the find() function in python, returning the starting index of the substring one is looking for. Commented Nov 15, 2019 at 21:13

1 Answer 1

1

To remove confounding variables, I replaced your unsupported find_sub calls with find, converted your infinite while to a for, and inserted a tracing print ... in short, standard debugging techniques.

def replace_sub(...
    for iter in range(10):
    # while True:
        print(final_pos, original_str[initial_pos:], substrings)
        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 = original_str[initial_pos:].find(old_sub)

print(replace_sub("Now is the time", 'e', '3'))

The output tells the tale:

9 Now is the time []
4  time ['Now is th']
4 s the time ['Now is th', '']
4 s the time ['Now is th', '', '']
4 s the time ['Now is th', '', '', '']
4 s the time ['Now is th', '', '', '', '']
4 s the time ['Now is th', '', '', '', '', '']
4 s the time ['Now is th', '', '', '', '', '', '']
4 s the time ['Now is th', '', '', '', '', '', '', '']
4 s the time ['Now is th', '', '', '', '', '', '', '', '']
3

You've fumbled your string subscripts, using an index based on the remaining fragment of original_str, but applying that from the start of the string. You loop because the two are no longer interchangeable after the first iteration.

Go back to your design, draw the references out on paper, and carefully update which index is used for what, and how to compute the proper offsets. Consider a local variable that contains only the remaining string, rather than trying to use initial_pos for inconsistent purposes.

Sign up to request clarification or add additional context in comments.

2 Comments

I wish all homework questions on here were answered this way. Just a perfect example of explaining the problem but in an instructional way that requires further work and understanding.
Thanks. Many homework questions are not amenable to this treatment. Although OP didn't follow all of the posting guidelines, there is a small enough functional gap, and a small enough problem, that a single print and a little guidance are enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.