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

Replace Character

Replace matching text with str.replace. Students read a target and replacement, preserve the source string, and learn that the API accepts substrings too.

IntermediatePhase 5 - Category 4: String TransformationExample 1 of 10
replace-character.py
1# Take string input
2s = input("Enter a string: ")
3old_char = input("Enter character to replace: ")
4new_char = input("Enter new character: ")
5
6# Replace
7result = s.replace(old_char, new_char)
8print(f"After replacement: {result}")

Output

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

In this one

  • Replace literal substrings
  • Keep source text unchanged
  • Understand all-match defaults

How it works

  1. 1

    Read source, target, and replacement text.

  2. 2

    Call s.replace(old_char, new_char).

  3. 3

    Print the returned result.

Edge cases

Can the target contain several characters?

Can the target contain several characters?

Yes. replace can match a substring.

Does this modify s in place?

Does this modify s in place?

No. It returns a new string.

What's going on

s.replace(old_char, new_char) returns a new string with every nonoverlapping match replaced. The prompt says character, but the API accepts longer text too.

Matching is case-sensitive. Replacing a with X in banana gives bXnXnX. An absent target leaves the content unchanged. An empty target has special insertion behavior, so a real one-character tool should validate the response length before calling replace.

Can the target contain several characters? Yes. replace can match a substring.

Does this modify s in place? No. It returns a new string.

Quiz

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

Question 1

How many matches are replaced by default?

Pick an answer to check it.

Question 2

Can the target contain several characters?

Pick an answer to check it.

Questions people ask

Can the target contain several characters?

Yes. replace can match a substring.

Does this modify s in place?

No. It returns a new string.

How many matches are replaced by default?

All nonoverlapping matches.