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)



Similar Reads

Python - Test if Substring occurs in specific position
Sometimes, while working with python strings, we can have a problem in which we need to test occurrence of substring. There is straight forward way to test this. But sometimes, we have a more specific problem in which we need to test if substring occurs at that particular position. Let's discuss certain ways in which this task can be performed. Met
6 min read
Python | Filter String with substring at specific position
Sometimes, while working with Python string lists, we can have a problem in which we need to extract only those lists that have a specific substring at a specific position. This kind of problem can come in data processing and web development domains. Let us discuss certain ways in which this task can be performed. Method #1: Using list comprehensio
7 min read
Python | Filter String with substring at specific position
Sometimes, while working with Python string lists, we can have a problem in which we need to extract only those lists that have a specific substring at a specific position. This kind of problem can come in data processing and web development domains. Let us discuss certain ways in which this task can be performed. Method #1: Using list comprehensio
5 min read
Find line number of a specific string or substring or word from a .txt file in Python
Finding the line number of a specific string and its substring is a common operation performed by text editors or any application with some level of text processing capabilities. In this article, you will learn how to find line number of a specific string or substring or word from a .txt (plain text) file using Python. The problem in hand could be
4 min read
Python | Index specific cyclic iteration in list
The problem of cyclic iteration is quite common, but sometimes, we come through the issue in which we require to process the list in a way in which it is cyclically iterated to starting from a specific index. Let's discuss certain ways in which this problem can be solved. Method #1 : Using % operator + loop The % operator can be used to cycle the o
6 min read
Python VLC MediaList - Removing Media from specific index
In this article we will see how we can remove the specific media through index in the MediaList object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediaList object contains the multiple media, in other words it has li
2 min read
PyQt5 - Change the item at specific index in ComboBox
In this article we will see how we can change the content of item at the specific index in combo box. In order to do this we will use setItemText method. Syntax : combo_box.setItemText(index, item) Argument : It takes two argument one is integer and second is string Action performed : This will change the content at that specific index Steps for im
2 min read
PyQt5 - Getting the content of item at specific index in ComboBox
In this article we will see how we can get the content of item at specific index in the combo box. In order to do this we will use the itemText method. Syntax : combo_box.itemText(index) Argument : It takes integer as argument Return : It return string i.e content of item Steps for implementation - 1. Create a combo box 2. Add items to combo box 3.
2 min read
Python | Get the starting index for all occurrences of given substring
Given a string and a substring, the task is to find out the starting index for all the occurrences of a given substring in a string. Let's discuss a few methods to solve the given task. Method #1: Using Naive Method C/C++ Code # Python3 code to demonstrate # to find all occurrences of substring in # a string # Initialising string ini_string = 'xbze
3 min read
Python - Filter the List of String whose index in second List contains the given Substring
Given two lists, extract all elements from the first list, whose corresponding index in the second list contains the required substring. Examples: Input : test_list1 = ["Gfg", "is", "not", "best", "and", "not", "CS"], test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "thats ok"], sub_str = "ok" Output : ['Gfg', 'is', 'best', 'an
10 min read
Practice Tags :