Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Replace Character Recursively

Replace matching characters through a recursive text scan. Students carry old and new values, advance an index, and rebuild a string without changing the source.

AdvancedPhase 3 - Level 4: String-based RecursionExample 5 of 10
replace-character-recursively.py
1def replace_char(s, old, new, index=0):
2 # Base case
3 if index >= len(s):
4 return ""
5
6 # Check current character
7 if s[index] == old:
8 char = new
9 else:
10 char = s[index]
11
12 # Recurse
13 return char + replace_char(s, old, new, index + 1)
14
15# Test
16text = input("Enter a string: ")
17old_char = input("Enter character to replace: ")
18new_char = input("Enter new character: ")
19result = replace_char(text, old_char, new_char)
20print(f"Result: {result}")

Output

Enter a string: Hello
Enter character to replace: l
Enter new character: x
Result: Hexxo

In this one

  • Choose a replacement per position
  • Carry unchanged search arguments
  • Rebuild immutable text

How it works

  1. 1

    Return empty text at the terminal index.

  2. 2

    Select new or the original indexed character.

  3. 3

    Join it with the recursive result for index + 1.

Edge cases

Does old = ab match a source substring?

Does old = ab match a source substring?

No. The code compares one character at a time.

Can new contain several characters?

Can new contain several characters?

Yes. Each matching source character is replaced by that whole string.

What's going on

At each index, the function chooses either new or the original character. It joins that choice to the recursively processed remainder.

The length check returns an empty tail at the end. Matching is case-sensitive. Since each comparison uses one source character, a multi-character old value cannot match; a multi-character replacement can expand the output. Pending concatenations use the call stack.

Does old = ab match a source substring? No. The code compares one character at a time.

Can new contain several characters? Yes. Each matching source character is replaced by that whole string.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is returned at the end index?

Pick an answer to check it.

Question 2

Does old = ab match a source substring?

Pick an answer to check it.

Questions people ask

Does old = ab match a source substring?

No. The code compares one character at a time.

Can new contain several characters?

Yes. Each matching source character is replaced by that whole string.

What is returned at the end index?

An empty string.