Open In App

Add Substring at Specific Index Python

Last Updated : 18 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Python, String is an immutable datatype, what this means is, that there are lot many restrictions when one handles its manipulation. The problem of adding something at a position at string is not possible, without the list reconstruction. Let’s discuss certain ways in which this task can be performed in Python

Ways to Insert Character Into String in Python

There are various ways to insert characters into strings in Python. here, we are discussing some generally used methods to insert characters into strings in Python those are following.

Create Two Different Strings

In this example, Python code initializes a string variable test_string with the value ‘geeksgeeks’ and another variable add_string with the value “for”. It then prints the original string .

Python3




# Python3 code to demonstrate
# Add substring at specific index
# using list slicing
 
# initializing string
test_string = 'GeeksGeeks'
 
# initializing add_string
add_string = "for"
 
# printing original string
print("The original string : " + test_string)
 
# printing add string
print("The add string : " + add_string)


Output :

The original string : GeeksGeeks
The add string : for

Add substring Using list slicing

This task can be performed using the list slicing. In this, we just slice the list into two parts, breaking at the target position and then rejoining it after inserting the target substring in the middle. 

Example :In this example code initializes a variable `N` with the value 5. It then uses list slicing to insert a substring (`add_string`) at the 5th index of the string `test_string`. The result is stored in the variable `res`, and the modified string is printed.

Python3




# initializing N
N = 5
 
# using list slicing
# Add substring at specific index
res = test_string[ : N] + add_string + test_string[N : ]
     
# print result
print("The string after performing addition : " + str(res))


Output :

GeeksforGeeks

Time complexity: O(1)
Auxiliary space: O(1)

Add a String in a Certain position using join() + list() + insert()

Another possible hack that can be performin for the following problem is that converting the string to list and then adding the string at particular position and then performing the join. 

Example :In this example code initializes a variable `N` with the value 5. It then inserts a substring (`add_string`) at the specified index (`N`) within a given string (`test_string`). The modified string is printed as the result.

Python3




# initializing N
N = 5
 
# using join() + list() + insert()
# Add substring at specific index
res = list(test_string)
res.insert(N, add_string)
res = ''.join(res)
     
# print result
print("The string after performing addition : " + str(res))


Output :

GeeksforGeeks

Time Complexity: O(n)
Auxiliary Space: O(n)

Insert character at specific index in string by String Concatenation

To concatenate substrings in a string, use the “substring” method to extract a portion of the original string. Then, use string concatenation by adding the extracted substring to another string using the “+” operator.

Example : In this example code initializes a variable N with the value 5. It then uses string concatenation to insert the contents of the variable add_string into the test_string at the 5th index.

Python3




# initializing N
N = 5
 
# using string concatenation
# Add substring at specific index
res = test_string[:N] + add_string + test_string[N:]
     
# print result
print("The string after performing addition : " + str(res))


Output :

GeeksforGeeks

Time Complexity: O(n)
Auxiliary Space: O(n)

Add a Character to a String at a certain Index Python using str.format()

To add a substring using str.format() in Python, use curly braces {} as placeholders within the string. Insert the desired substring or variable inside the curly braces, and then use the format() method to replace the placeholders with the specified values.

Example : In this example code inserts the string `add_string` at the 5th position in the variable `test_string` and stores the result in `new_string`. It utilizes the `format` method to concatenate the substring before and after the specified position.

Python3




position = 5
 
new_string = "{}{}{}".format(test_string[:position], add_string, test_string[position:])
print(new_string)


Output :

GeeksforGeeks

Time Complexity: O(n)
Auxiliary Space: O(n)

Add an Element to a String in a Specific Index using bytearray

To add a substring using bytearray in Python, first, convert the original string to a bytearray. Then, use slicing to insert the desired substring at the desired position. Finally, convert the bytearray back to a string if needed.

Example : In this example the code inserts a string (`add_string`) into another string (`test_string`) at a specified position (`position`) using a bytearray. The bytearray is created from the original string, and the insertion is performed by replacing a slice with the bytes of the additional string.

Python3




position = 5
 
bytearray_string = bytearray(test_string, 'utf-8')
bytearray_string[position:position] = bytes(add_string, 'utf-8')
 
new_string = bytearray_string.decode('utf-8')
print(new_string)


Output :

GeeksforGeeks

Time Complexity: O(n)
Auxiliary Space: O(n)

Insert Character Into String in Python using regular expressions (re module)

To add a substring using the re module in Python, import the re module. Then, use the re.sub() function, specifying the pattern to match and the replacement string. Finally, apply re.sub() to the target string, and the modified string with the added substring will be returned.

Example : In this example code uses the `re.sub` function to insert a specified string (`add_string`) at the 7th position in the `test_string`. The regular expression `(.{{{position}}})` captures the first 7 characters, and the replacement `\1{add_string}` inserts the additional string at that position.

Python3




position = 7
 
new_string = re.sub(f'(.{{{position}}})', f'\\1{add_string}', test_string)
print(new_string)


Output :

GeeksforGeeks

Time Complexity: O(n)
Auxiliary Space: O(n)

Insert an element at specific index using f-string

To add a substring using f-strings in Python, enclose the desired substring within curly braces {} and insert it within an f-string, along with other variables or text.

Example :In this example code inserts the string `add_string` into `test_string` at the specified `index`, creating a new string `result_str`, and then prints the result.

Python3




index = 5
 
# Adding substring
result_str = f"{test_string[:index]}{add_string}{test_string[index:]}"
 
# Printing the result
print(result_str)


Output :

GeeksforGeeks

Time Complexity: O(n)
Auxiliary Space: O(n)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads