Sanitize Field
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
Problem
Our exported records still carry a retired label, sometimes more than once inside the same text value. Return text with every occurrence of old swapped for new, and leave it untouched when old never appears.
Dirty input. Clean output.
Example 1
Input:
text = "status: legacy_ok, prev: legacy_ok", old = "legacy_ok", new = "ok"
Output:
"status: ok, prev: ok"
Example 2
Input:
text = "aaa", old = "a", new = "b"
Output:
"bbb"
Worked solution and explanation
Why this problem exists in real interviews
This is find-and-replace in a cleanup costume, and the logic is one call. What actually trips people is the contract: the grader calls str_replace(text=..., old=..., new=...) by keyword, so a function whose first parameter is named anything other than text raises TypeError before it replaces a single character. Match the signature, then make sure the replacement covers every occurrence, an empty new, an empty text, and a pattern that never shows up.
Break down the requirements
Step 1: Find and replace all occurrences
Every instance of old is swapped, not just the first, so a label repeated in one value is fully cleaned. An empty new deletes the label outright, and a text with no match comes back unchanged.
The solution
def str_replace(text, old, new):
cleaned = text.replace(old, new)
return cleanedCommon follow-up questions
- How would you implement replace from scratch? (Tests manual scanning with `str.find()` in a loop and string concatenation.)
- What if the replacement creates new instances of the pattern? (Tests whether the replacement should be applied recursively or just once (standard replace does a single pass).)
- What if the replacement is regex-based? (Tests using `re.sub(pattern, replacement, text)` for pattern-based substitution.)