Insert String Into a String in Python

  1. Insert String Into a String in Python Using the string.find() Method
  2. Insert String Into a String in Python Using the list.insert() Method

This tutorial will explain the multiple methods to insert a string into an existing string. We should know that in Python strings are immutable, which means that a string can not be changed or modified in Python.

What we can do regarding the string insertion is to create a new string with the desired changes, like splitting the original string and inserting a new string in it.

Insert String Into a String in Python Using the string.find() Method

We first use the string.find() method to get the substring index in the string, after which we need to insert another string. After getting the substring index, we split the original string and then concatenate the split strings and the string we need to insert using the + operator to get the desired string.

Example code:

my_string = 'Hello, what are doing?'
index = my_string.find('doing')
final_string = my_string[:index] + 'you ' + my_string[index:]
print(final_string)

Output:

Hello, what are you doing?

Insert String Into a String in Python Using the list.insert() Method

We can insert the string into another string after splitting the original string into a list using the string.split() function. After the string is converted into the list, we can insert the string at the list’s desired index, using the list.insert() function.

After splitting and adding the desired string, we can convert the list back into the string using the string.join() function and get the required string.

Example code:

my_string = 'Hello, what are doing'

split_strings = my_string.split()
split_strings.insert(3, 'you')
final_string = ' '.join(split_strings)
print(final_string)

Output:

Hello, what are you doing?
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python String

  • Remove Whitespace From a String in Python
  • Check a String Contains a Number in Python