How to Insert a String into Another String at a Given Index in Python? 

Rate this post

Let’s start this article with a quick question to understand your understanding of strings.

💬 Question: Can the string objects be modified in Python?

What do you think? Well, the fact is String objects are immutable. They cannot be modified.

Consider the below example : 

word="Finxter"
word[3]="a"

Output:

Traceback (most recent call last):
  File "C:\Users\paian\PycharmProjects\DemoProject\main.py", line 27, in <module>
    word[3]="a"
TypeError: 'str' object does not support item assignment

Now you might say, replacement operations and insertion operations in strings are common. Yes, that’s true.

But while replacing/inserting, the existing string object does not change, a new object instance gets created with the changes.

Let’s understand this with an example.

word="Finxter"
print(f"The object instance id of \033[1m{word}\033[0m is \033[1m{id(word)}\033[0m")
print(f"The object instance id of \033[1m{word.replace('i','q')}\033[0m is \033[1m{id(word.replace('i','q'))}\033[0m")

Output:

The object instance id of Finxter is 2625736175792
The object instance id of Fqnxter is 2625736175728

As seen from the above example, the instance id of the existing string and the modified string are different. This means that every time we modify a string object a new string object is created.

Now that we have understood what happens in the background, let’s learn how to insert a string within the given string in a given index.

Method 1: Using Slicing

As seen in the first example above, we cannot simply assign a new value to a particular index. 

Consider a sample string "Let's learn programming". Now, let’s say we have to insert the string "Python" before the word "programming".

In this case, we have to,

  • Find the index where the word "programming" starts.
  • Now, insert the word "Python" in the required position using string slicing.

Consider the following code snippet,

word="Let’s learn programming"

#Find the index at which the word starts
index=word.find("programming")

#Add the required word using slicing
print(word[:index]+"Python "+word[index:])

Output:

Let’s learn Python programming

In the above example, we found the index where the word "programming" starts and then inserted the string before that word.

If the specified string (example, "programming") is not present, find() returns -1, and the required string is inserted in the last but one index as shown below.

word="Let’s learn programming"

#Find the index at which the word starts
index=word.find("order")

print(word[:index]+"Python "+word[index:])

Output:

Let’s learn programminPython g

To avoid cases like this, we can have an if-else block to insert the string only if the given string exists. Refer to the below example for more details.

word="Let’s learn programming"
index_word= "order"
#Find the index at which the word starts
index=word.find(index_word)

if index > -1 :
   #Add the required word using slicing
   print(word[:index]+"Python "+word[index:])
else:
   print(f"Please specify the right index where the string has to be inserted. The word \"{index_word}\" is not present in the given string ")

Output:

Please specify the right index where the string has to be inserted. The word “order” is not present in the given string 

💡 Note: find() returns the index of the first occurrence of a matching string.

If you know the index at which a string has to be inserted, you can directly insert it at that index. For example, if you want to insert some string at index 12, run the following code snippet.

word="Let’s learn programming"
index=12
print(word[:index]+"Python "+word[index:])

Output:

Let’s learn Python programming

Method 2: Using list.insert()

The first method mentioned above comes in handy when you have to insert a string with respect to a substring in the string.

However, is there another method if we already have the index where we want to insert the string? The answer is yes!

Let’s divide the problem and then find the solution. 

  • We have to first convert the given string to a list.
  • Get the index at which some string has to be inserted.
  • Insert the string in the given string using insert()
  • Convert the list back to the string.

Now, let’s insert the string "Python" in the string "Let’s learn Programming" using this method.

word="Let’s learn programming"
#index at which the string has to be inserted
index=2

#convert the word to list
lst_word=word.split()

#insert the string at required index
lst_word.insert(index, "Python")

#Join the list to a string using
print(" ".join(lst_word))

Output:

Let’s learn Python programming

Runtime Comparison

Now, let’s check the execution time using both methods for this sample example.

word="Let’s learn programming"
################ Using Method 1 : Slicing ##################
start=perf_counter_ns()
index_word="programming"
#Find the index at which the word starts
index=word.find(index_word)
if index > -1 :
   final_word= word[:index]+"Python " + word[:index]
end=perf_counter_ns()
print(f"The exceution time using slicing is {end-start}ns")

################ Using Method 2 : list.insert() #############

#index at which the string has to be inserted
index=2
start=perf_counter_ns()
#convert the word to list
lst_word=word.split()

#insert the string at reuired index
lst_word.insert(index,"Python")

#Join the list to a string using
final_word = " ".join(lst_word)
end=perf_counter_ns()

print(f"The execution time using list.insert() method  is {end-start}ns")

Output:

The exceution time using slicing is 3700ns
The execution time using list.insert() method  is 3800ns

Conclusion

That brings us to the end of this article.

In this article, we understood how the string modification works internally.

Also, we have discovered two different ways of inserting a sub-string in the given string at a given index.

We hope this article has been informative. Stay tuned to us and subscribe to our email academy for more such content.