Add Substring at Specific Index Python
Last Updated :
18 Dec, 2023
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
Remove Character in a String at a Specific Index in Python
Removing a character from a string at a specific index is a common task when working with strings and because strings in Python are immutable we need to create a new string without the character at the specified index. String slicing is the simplest and most efficient way to remove a character at a
2 min read
Find the Index of a Substring in Python
Finding the position of a substring within a string is a common task in Python. In this article, we will explore some simple and commonly used methods to find the index of a substring in Python.Using str.find() The find() method searches for the first occurrence of the specified substring and return
3 min read
How to Create a String of Specified Length in Python
Creating a string of a specific length in Python can be done using various methods, depending on the type of string and its contents. Letâs explore the most common techniques to achieve this.The simplest way to create a string of a specified length is by multiplying a character or sequence of charac
2 min read
How to Get Index of a Substring in Python?
To get index of a substring within a Python string can be done using several methods such as str.find(), str.index(), and even regular expressions. Each approach has its own use case depending on the requirements. Letâs explore how to efficiently get the index of a substring.The simplest way to get
2 min read
Python | Add one string to another
The concatenation of two strings has been discussed multiple times in various languages. But the task is how to add to a string in Python or append one string to another in Python. Example Input: 'GFG' + 'is best' Output: 'GFG is best' Explanation: Here we can add two string using "+" operator in Py
5 min read
How to Remove a Substring in Python?
In Python, removing a substring from a string can be achieved through various methods such as using replace() function, slicing, or regular expressions. Depending on your specific use case, you may want to remove all instances of a substring or just the first occurrence. Letâs explore different ways
2 min read
Python - Get all substrings of given string
A substring is any contiguous sequence of characters within the string. We'll discuss various methods to extract this substring from a given string by using a simple approach. Using List Comprehension :List comprehension offers a concise way to create lists by applying an expression to each element
3 min read
Python - Word starting at Index
Sometimes, while working with Python, we can have a problem in which we need to extract the word which is starting from a particular index. This can have a lot of applications in school programming. Let's discuss certain ways in which this task can be performed. Method #1: Using a loop This is a bru
2 min read
How to Find Index of a Substring in Python
In Python, sometimes we need to know where a certain substring appears in a string. To do this, we can find the index (or position) of that substring. The index tells us where the substring is located. Letâs look at some simple ways to find the index of a substring in a string.Using find() methodThe
2 min read
Python - Avoid Spaces in string length
When working with strings in Python, we may sometimes need to calculate the length of a string excluding spaces. The presence of spaces can skew the length when we're only interested in the number of non-space characters. Let's explore different methods to find the length of a string while ignoring
3 min read