# Sanitize Field

> Dirty input. Clean output.

Canonical URL: <https://datadriven.io/problems/sanitize_field>

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given strings s, old, new, return s with every occurrence of old replaced by new.

## Worked solution and explanation

### Why this problem exists in real interviews

Replacing all occurrences of a substring tests whether you know `str.replace()` or can implement it manually. It is the simplest string transformation in ETL.

---

### Break down the requirements

#### Step 1: Find and replace all occurrences

Replace every instance of the old substring with the new one throughout the string.

---

### The solution

**Built-in substring replacement**

```python
def sanitize(text, old, new):
    result = text.replace(old, new)
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n * m) in the worst case where n is the string length and m is the pattern length for each scan position.
> 
> **Space:** O(n) for the new string.

> **Interviewers Watch For**
>
> Whether you use the built-in `str.replace()`. If the interviewer asks you to implement it manually, they want to see string scanning and rebuilding logic.

> **Common Pitfall**
>
> Assuming `replace` only replaces the first occurrence. Python's `str.replace()` replaces all occurrences by default unless a count argument is specified.

---

## Common 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.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/sanitize_field)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.