Search⌘ K
AI Features

Modifying Strings: Inserting, Deleting, and Replacing Characters

Explore how to modify strings in Python despite their immutability. Learn methods to insert delete and replace characters and substrings efficiently by using list conversion slicing and concatenation. Understand the underlying time complexity of these operations to write optimized string manipulation code.

By now, you understand that strings in Python are immutable and that every operation that appears to modify a string actually produces a new one. That raises a practical question that needs a direct answer: if strings cannot be changed in place, how do you perform the kinds of modifications that real programs and algorithms constantly require? Inserting a character at a specific position, removing an unwanted character, and replacing one substring with another are fundamental operations. Understanding how to perform them correctly and efficiently is what well cover now.

Inserting a character

Inserting a character at a specific position means placing a new character at a given index and shifting every character from that position onward one step to the right to accommodate it.

Consider the string "helo" and the requirement to insert the character 'l' at index 3.

Before: h e l o
Index: 0 1 2 3
After: h e l l o
Index: 0 1 2 3 4

The character 'o' that was at index 3 has moved to index 4 to make room for the inserted character. In general, inserting at position ii requires shifting every character from index ii to the end of the string one position to the right. In the worst case, inserting at the beginning of the string requires shifting all nn existing characters, making insertion an O(n)O(n) operation.

Insertion method 1

In Java, because strings are immutable, insertion is implemented using a StringBuilder. The insert(int offset, char ch) method places the character at the given index, shifting all subsequent characters one position to the right.

Java 25
class Main {
public static void main(String[] args) {
String s = "helo";
StringBuilder sb = new StringBuilder(s);
sb.insert(3, 'l');
String result = sb.toString();
System.out.println("Original string: \"" + s + "\"\n"); // Original string: helo
System.out.println("After insertion: \"" + result + "\""); // After insertion: hello
}
}

The StringBuilder conversion costs O(n)O(n), the insertion costs O( ...