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.
1# Take string input2s = input("Enter a string: ")3old_char = input("Enter character to replace: ")4new_char = input("Enter new character: ")56# Replace7result = 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
Read source, target, and replacement text.
- 2
Call s.replace(old_char, new_char).
- 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.
๐Related Content
- ๐
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- ๐
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- ๐ป
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum