Strings in Python are a fundamental data type used to represent text. A common manipulation task is inserting a substring into an existing string at a specific position, whether it's the exact middle, a specific index, or replacing a placeholder.
However, Python strings are immutable, meaning they cannot be changed after they are created. To "insert" a string, you must actually construct a new string that combines the original parts with the new content. This guide explores the most efficient and readable ways to achieve this.
Understanding String Immutability
Before inserting text, it is crucial to understand that you cannot modify a string in place using an index assignment.
text = "Hello world"
try:
text[6] = "Python "
except TypeError as e:
print(f"Error: {e}")Output:
Error: 'str' object does not support item assignmentTo achieve the desired result, we must create a new string variable.
Method 1: Slicing and Concatenation (Standard)
The most algorithmic approach is to split the original string into two parts (left and right) based on the insertion index and concatenate them with the new string in the middle.
Calculating the Middle Index
To insert exactly in the middle, calculate the index using integer division //.
original_text = "Helloworld"
insert_text = " Python "
mid_index = len(original_text) // 2
new_text = original_text[:mid_index] + insert_text + original_text[mid_index:]
print(f"Original: {original_text}")
print(f"Result: {new_text}")Output:
Original: Helloworld
Result: Hello Python worldMethod 2: Using F-Strings (Recommended)
Introduced in Python 3.6, F-strings provide a concise and readable way to embed expressions inside string literals. This is often cleaner than using the + operator multiple times.
original = "I love coding"
insertion = "Python "
index = 7 # Insert after "I love "
result = f"{original[:index]}{insertion}{original[index:]}"
print(result)Output:
I love Python codingMethod 3: List Conversion (For Mutable Operations)
If you need to perform multiple insertions or complex manipulations, converting the string to a List is efficient. Lists are mutable, so you can use the .insert() method. Afterward, you join the list back into a string.
text = "OpenAI"
to_insert = "-"
char_list = list(text)
print(f"List: {char_list}")
char_list.insert(4, to_insert)
result = "".join(char_list)
print(f"Result: {result}")Output:
List: ['O', 'p', 'e', 'n', 'A', 'I']
Result: Open-AIPractical Example: Formatting Filenames
A common use case for string insertion is modifying filenames, such as adding a timestamp or a version number before the file extension.
import time
filename = "report.pdf"
timestamp = "_2025"
dot_index = filename.rfind(".")
if dot_index != -1:
new_filename = f"{filename[:dot_index]}{timestamp}{filename[dot_index:]}"
else:
new_filename = f"{filename}{timestamp}"
print(f"Old Name: {filename}")
print(f"New Name: {new_filename}")Output:
Old Name: report.pdf
New Name: report_2025.pdfConclusion
Since Python strings are immutable, insertion always involves creating a new string.
- Use Slicing + F-strings (
f"{s[:i]}{new}{s[i:]}") for the most readable and modern approach. - Use Slicing + Concatenation (
s[:i] + new + s[i:]) for compatibility with older Python versions. - Use List Conversion (
list(s)) if you need to perform multiple heavy modifications before finalizing the string.