Search⌘ K
AI Features

Modifying Strings: Inserting, Deleting, and Replacing Characters

Explore fundamental string modification techniques in Python, including inserting, deleting, and replacing characters and substrings. Understand the implications of string immutability and how to efficiently create new modified strings using slicing, list conversion, and built-in functions.

By now you have established the understanding that strings in Python are immutable and that every operation which appears to modify a string is actually producing a new one. That raises a practical question that needs a direct answer: if strings cannot be changed in place, how does one actually perform the kinds of modifications that real programs and algorithms constantly require? Inserting a character at a specific position, removing an unwanted character, replacing one substring with another, these are fundamental operations, and understanding how to perform them correctly and efficiently is what we’ll learn 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 Python, as strings are immutable, insertion is implemented by converting the string to a list of characters, performing the insertion on the list, and joining the result back into a string. The insert(i, x) method places the element x at index i, shifting all subsequent elements one position to the right.

Python 3.14.0
s = "helo"
chars = list(s)
chars.insert(3, 'l')
result = "".join(chars)
print(f'Original string: "{s}"\n') # Original string: helo
print(f'After insertion: "{result}"') # After insertion: hello

The list conversion costs O(n)O(n) ...