str.replace() — Python Technical Interview Questions & Answers

str.replace()

str.replace()

  • str.replace is a string helper. You call it on text like "Asha" or "banana". It gives a new string (or a number/True-False). The old string does not change unless you assign the result back.
  • str.replace() — output: Asha Delhi.
  • Fresher trap: writing s.str.replace() and expecting s to update. Strings are immutable. Write s = s.str.replace(...) if you need the new value (when it returns a string).

Technical Interview Tip: Call str.replace on one real word and say what prints.

Code Examples for str.replace()

Example

# str.replace()
print("Asha Pune".replace("Pune", "Delhi"))

str.replace() — output: Asha Delhi.

How to Explain str.replace() to an Interviewer

Explain str.replace() as if you are teaching a junior — definition, then one tiny script.

str.replace works on str. str.replace usually returns a new string.

What does the example print, and why?

str

What mistake do freshers make with str.replace()?

str.replace does not change the original string in place.