Python Program to Insert a string into another string


In Python, we can insert a string into another string using the string concatenation method, string interpolation method, and using replace() method. Python provides various ways to insert a string into another string. In this article, we will understand all the methods with the help of suitable examples.

Method 1: Using the Concatenation Operator

String concatenation simply joins two strings together using the (+) operator. Any number of strings can be concatenated using this method in a simple and effective way.

Example

In the below example, we initialized three strings namely string1, string2, and inserted_string. We need to insert the inserted_string in the middle of the other two strings. The string concatenation method can be used here as follows −

string1 = "Hello, "
string2 = "world!"
inserted_string = "Python "
new_string = string1 + inserted_string + string2
print(new_string)

Output

Hello, Python world!

Method 2: Using the String Interpolation

String interpolation is used for inserting variables or expressions into a string. In Python, we can use the f-string syntax to interpolate a dynamic string into our original string. The f string starts with the letter f.

Example

In the below example, we initialize three strings namely string1 and string2 and inserted_string. All these three strings can be interpolated into a new string with inserted_string in between the string1 and string2 using f-string. The code for the same is as follows −

string1 = "Hello, "
string2 = "world!"
inserted_string = "Python"
new_string = f"{string1}{inserted_string} {string2}"
print(new_string)

Output

Hello, Python world!

Method 3: Using the str.replace() method

The replace() method in Python replaces all the occurrences of a substring with a new string. The replace method takes the old_string, and new_string as input and returns the new string after the replacement of the substring.

Example

In the below example replace the substring “world” with a new string “Python”. The replace method is called with the old string as “world” and the new string as “Python”. Here is the code for the same −

string1 = "Hello, world!"
inserted_string = "Python"
new_string = string1.replace("world", inserted_string)
print(new_string)

Output

Hello, Python!

Conclusion

In this article, we discussed how to use string concatenation, string interpolation, and replace() methods to insert a string into another string. f -string can be used for string interpolation. Any of the three methods can be used for inserting a string into another string in Python.

Updated on: 17-Apr-2023

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements