Write a Python Function to Insert a String in The Middle of a String

In this article you will learn how to insert a second string in the middle of a given string. Lets ask the user to enter two strings, then use the python function and insert the string in the middle and print it on standard output.

Lets try defining a function and insert the string in the middle of the string.

 

Write a Python Function to Insert a String in The Middle of a String



Write a Python Function to Insert a String in The Middle of a String

Define a function named as  insert_string()  and pass to input arguments first and second strings.  inside the function calculate the length of the first string and perform two divisions by 2 to  middle index.

Append the second string in the middle of the first half of the given strings, and then append the second half of the given string, use the return statement and return the string.

def insert_string(first, second):
   middle = len(first) // 2
   return first[:middle] + second + first[middle:]



In the main program take two strings text1 and text2 ask the user to enter the first and second string. Use the print function to display the user friendly message and then use another print statement to call the function by passing two input strings.

The function will return the string and that will be printed on standard output using print() function call.

text1 = input("Enter First String : ")
text2 = input("Enter Second String : ")

print("Final string after inserting at middle is : ")
print(insert_string(text1, text2))




Complete Python Program
=========================

def insert_string(first, second):
middle = len(first) // 2
return first[:middle] + second + first[middle:]


text1 = input("Enter First String : ")
text2 = input("Enter Second String : ")

print("Final string after inserting at middle is : ")
print(insert_string(text1, text2))
 
 



Output 1
=============

Enter First String : how?
Enter Second String : ooooooooooooooo
Final string after inserting at middle is :
hoooooooooooooooow?





Output 2
==============

Enter First String : hi
Enter Second String : +
Final string after inserting at middle is :
h+i



Output 3
=================

Enter First String : i am a star
Enter Second String : meg
Final string after inserting at middle is :
i am mega star




Conclusion
=====================

Execute the above python program by providing two random strings as input to the python program, note down the result.

Comment it down below if you have any queries regarding the above the python program.




Post a Comment

0 Comments