Python - How to insert string at specific position


Python - Insert string at specific position

To insert a string at specific position within another string, you can use slicing and concatenation.

For example, if x is the original string, and you would like to insert y string at i position in the original string, then you can use the following expression.

x = x[:i] + y + x[i:]

When you insert a string y in x at index i, the character from the index i are shifted to right by the number of positions equal to the length of the other string y.

Examples

1. Insert 'banana' string in 'apple' string at index=2

In this example, the original string is 'apple' and the other string is 'banana'. We have to insert the other string at index=2 in the original string.

Python Program

x = 'apple'
y = 'banana'
i = 2

x = x[:i] + y + x[i:]
print(x)

Output

apbananaple

Explanation

a  p  p  l  e
0  1  2  3  4
      ↥
  insert 'banana' at index=2
a  p   (here comes the other string)    p  l  e
a  p  'b  a  n  a  n  a'  p  l  e