Programming
String Manipulation
Coding Tutorial
Python
Data Structures

Replace a character at a specific index in a string?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Replacing one character by index sounds like a tiny operation, but the right implementation depends on whether the language treats strings as mutable or immutable. In Python, Java, and JavaScript, strings are immutable, so the usual pattern is to create a new string with the desired replacement.

Python: Use Slicing

In Python, the simplest solution is to combine the prefix, the replacement character, and the suffix.

python
1def replace_char(text: str, index: int, new_char: str) -> str:
2    if len(new_char) != 1:
3        raise ValueError("new_char must be exactly one character")
4    if index < 0 or index >= len(text):
5        raise IndexError("index out of range")
6
7    return text[:index] + new_char + text[index + 1:]
8
9
10print(replace_char("hello", 1, "a"))

This prints hallo. The main advantage is clarity. The main tradeoff is that a new string is allocated.

Java: Use StringBuilder for Clarity

Java strings are also immutable, but StringBuilder gives a readable and efficient way to change one position before converting back.

java
1public static String replaceChar(String text, int index, char newChar) {
2    if (index < 0 || index >= text.length()) {
3        throw new IndexOutOfBoundsException("index out of range");
4    }
5
6    StringBuilder builder = new StringBuilder(text);
7    builder.setCharAt(index, newChar);
8    return builder.toString();
9}
10
11public static void main(String[] args) {
12    System.out.println(replaceChar("hello", 1, 'a'));
13}

This is usually better than manually combining substrings because the intent is obvious.

JavaScript: Rebuild the String

JavaScript follows the same immutable-string model, so you create a new string from two slices and the replacement.

javascript
1function replaceChar(text, index, newChar) {
2  if (newChar.length !== 1) {
3    throw new Error("newChar must be exactly one character");
4  }
5  if (index < 0 || index >= text.length) {
6    throw new RangeError("index out of range");
7  }
8
9  return text.slice(0, index) + newChar + text.slice(index + 1);
10}
11
12console.log(replaceChar("hello", 1, "a"));

For one-off replacements, this is perfectly fine and easy to understand.

Validate Inputs Explicitly

There are two edge cases you should decide on deliberately:

  • invalid index
  • replacement string longer than one character

Returning the original string silently can hide bugs. Throwing an error is usually better in library code because it makes misuse visible immediately. In user-facing code, you may prefer a safer wrapper that returns the original input or null depending on the API style.

Performance Changes When Replacing Repeatedly

If you need to replace many positions in a loop, building a new string every time can become wasteful. In that case, switch to a mutable intermediary such as a character array or StringBuilder.

python
1def replace_many(text: str, changes: dict[int, str]) -> str:
2    chars = list(text)
3    for index, new_char in changes.items():
4        chars[index] = new_char
5    return "".join(chars)
6
7
8print(replace_many("abcdef", {1: "X", 4: "Y"}))

The same principle applies in other languages: repeated mutation is cheaper on a mutable buffer than on many short-lived strings.

Choose an API That Matches Intent

If your code is specifically changing one character, a small helper function makes callers clearer than repeating slice logic everywhere. That helper is also the right place to define your behavior for bounds checks, negative indices, Unicode assumptions, and testing.

That matters more than the exact syntax. Good string utilities reduce duplicated low-level manipulation across a codebase.

Common Pitfalls

  • Forgetting that strings are immutable and expecting in-place modification.
  • Accepting multi-character replacements when the function is supposed to replace exactly one position.
  • Silently ignoring invalid indexes and making bugs harder to trace.
  • Rebuilding the whole string repeatedly inside performance-sensitive loops.
  • Confusing character positions with Unicode grapheme clusters in user-visible text.

Summary

  • In immutable-string languages, replacing a character means creating a new string.
  • Use slicing in Python and JavaScript for simple cases.
  • Use StringBuilder in Java for a clean, efficient implementation.
  • Validate index bounds and replacement length explicitly.
  • Switch to mutable buffers when many replacements happen in a loop.

Course illustration
Course illustration

All Rights Reserved.