Add Substring at Specific Index Python
Last Updated :
05 Jul, 2025
Adding a substring at a specific index in Python means creating a new string by combining slices of the original string with the inserted text, since strings are immutable. For example, inserting "for" at index 5 in "GeeksGeeks" results in "GeeksforGeeks".
Let’s explore several efficient ways to achieve this.
Using list slicing
This is the most straightforward method. We split the string into two parts and insert the new string in between.
Python
s = "GeeksGeeks"
add = "for"
i = 5
res = s[:i] + add + s[i:]
print(res)
Explanation:
- s[:i] gives "Geeks" before index i , s[i:] gives "Geeks" after index i and add = "for" is inserted in between.
- s[:i] + add + s[i:] → "Geeks" + "for" + "Geeks" = "GeeksforGeeks"
Using join()
We convert the string to a list, insert the new string at the desired position and then join it back into a string.
Python
s = "GeeksGeeks"
add = "for"
i = 5
a = list(s)
a.insert(i, add)
res = ''.join(a)
print(res)
Explanation:
- list(s) creates a list of characters from the string s and a.insert(i, add) inserts the string "for" at index i as a single element.
- ''.join(a) combines the list back into a single string, inserting "for" at the specified position.
format() function insert a substring at a specific index by slicing the original string and combining the parts with placeholders.
Python
s = "GeeksGeeks"
add = "for"
i = 5
res = "{}{}{}".format(s[:i], add, s[i:])
print(res)
Explanation:
- {} placeholders are used for formatting
- s[:i], add and s[i:] are passed into format() in order
Using f-string
An f-string is a cleaner and modern way of formatting strings. It makes the code more readable and concise, especially when inserting values directly into strings.
Python
s = "GeeksGeeks"
add = "for"
i = 5
res = f"{s[:i]}{add}{s[i:]}"
print(res)
Explanation:
- f-strings evaluate expressions inside {}
- This directly inserts "for" at the desired index
Using re.sub()
're' module insert a substring at a specific index. We match the first i characters using a regex pattern and then add the new string right after the match.
Python
import re
s = "GeeksGeeks"
add = "for"
i = 5
res = re.sub(f"(.{{{i}}})", f"\\1{add}", s)
print(res)
Explanation:
- The pattern (.{{{i}}}) captures the first i characters
- \\1{add} inserts the substring after the matched portion
Related Articles:
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice