Skip to main content

How to Insert a String into the Middle of Another String in Python

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:
# ⛔️ Incorrect: Strings do not support item assignment
# Trying to insert 'Python' manually at index 6
text[6] = "Python "
except TypeError as e:
print(f"Error: {e}")

Output:

Error: 'str' object does not support item assignment

To 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 "

# 1. Calculate the middle index
mid_index = len(original_text) // 2

# 2. Slice the string: Start-to-Middle + Insert + Middle-to-End
# [:mid_index] gets characters from 0 up to (but not including) mid_index
# [mid_index:] gets characters from mid_index to the end
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 world

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 "

# ✅ Correct: Embedding slices directly into an f-string
result = f"{original[:index]}{insertion}{original[index:]}"

print(result)

Output:

I love Python coding

Method 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 = "-"

# 1. Convert string to a list of characters
char_list = list(text)
print(f"List: {char_list}")

# 2. Insert character at index 4
char_list.insert(4, to_insert)

# 3. Join the list back into a string
result = "".join(char_list)

print(f"Result: {result}")

Output:

List: ['O', 'p', 'e', 'n', 'A', 'I']
Result: Open-AI
note

list.insert() inserts a single element. If you insert a multi-character string like "XYZ" into the list, it will appear as a single element in the list, but .join() handles it seamlessly

Practical 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"

# Find the position of the dot (extension separator)
dot_index = filename.rfind(".")

if dot_index != -1:
# Insert timestamp before the dot
new_filename = f"{filename[:dot_index]}{timestamp}{filename[dot_index:]}"
else:
# No extension found, append to end
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.pdf

Conclusion

Since Python strings are immutable, insertion always involves creating a new string.

  1. Use Slicing + F-strings (f"{s[:i]}{new}{s[i:]}") for the most readable and modern approach.
  2. Use Slicing + Concatenation (s[:i] + new + s[i:]) for compatibility with older Python versions.
  3. Use List Conversion (list(s)) if you need to perform multiple heavy modifications before finalizing the string.