Python | Add substring at specific index

Method # 1: Using List Slicing

This task can be accomplished using List Slicing. In doing so, we simply slice the list in two, splitting at the target position and then rejoining it after inserting the target substring in the middle.

# Python3 demo code
# Add a substring at a specific index
# using list slicing

 
# initialization string

test_string = `geeksgeeks`

  
# initializing add_string

add_string = "for"

 
#print original strings

print ( "The original string : " + test_string)

  
# print add line

print ( "The add string:" + add_string)

 
# initialization N

N = 5

 
# using list slicing
# Add a substring at a specific index

res = test_string [: N]  + add_string + test_string [N:]

 
# print result

print ( "The string after performing addition:" + str (res))

Output:

 The original string: geeksgeeks The add string: for The string after addition: pythonengineering 

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

Another possible hack that can be done for the next problem is to convert the string to a list and append the string at a specific position and then do the join.

 

# Python3 demo code
# Add a substring at a specific index
# using join ( ) + list () + insert ()

 
# initializing string

test_string = `geeksgeeks`

 
# initializing add_string

add_string = "for"

 
# print original line

print ( "The original string:" + test_string)

 
# print add line

print ( "The add string:" + add_string)

 
# initialization N

N = 5

 
# using join () + list () + insert ()
# Add a substring at a specific index

res = list (test_string)

res.insert (N, add_string)

res = `` .join (res)

 
# print result

print ( "The string after performing addition:" + str (res))

Exit:

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