Python | Add substring at specific index

In Python, String is 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.

Method #1 : 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 target substring at middle.



filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)
  
# 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))

chevron_right


Output :

The original string : geeksgeeks
The add string : for
The string after performing addition : geeksforgeeks

 

Method #2 : Using join() + list() + insert()

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# Add substring at specific index
# using join() + list() + insert()
  
# 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)
  
# 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))

chevron_right


Output :

The original string : geeksgeeks
The add string : for
The string after performing addition : geeksforgeeks


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.