Prove Strings Are Immutable

Easy ⏱ 8 min 87% acceptance ★★★★☆ 4.3
Strings in Python cannot be modified in place — s[0] = 'H' raises a TypeError. Write replace_char_at(s, index, new_char) that returns a new string with the character at index swapped for new_char, built entirely from slices (never mutating s).

Examples

Example 1
Input
s = 'hello', index = 0, new_char = 'H'
Output
'Hello'
Explanation

The character at index 0 is swapped; everything else is copied through.

Example 2
Input
s = 'cat', index = 2, new_char = 'r'
Output
'car'
Explanation

Works for any valid index, including the last one.

Constraints

  • 0 <= index < len(s)
  • len(new_char) == 1

Topics

StringsImmutability

Companies

IBMOracle

Hints

Hint 1

Build the result as s[:index] + new_char + s[index+1:].

Hint 2

This never touches `s` itself — it constructs a brand-new string object.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.