Given two strings as input to the Python program you have to take the first string and divide into 2 parts then take the second string and insert the second string into the middle of the first string.
Lets try this using the python function.
Write A Python Function To Insert A String In The Middle Of A String
Lets define a function named as middle(), pass the two string variables as input to the python function i.e, text1 and text2.
Divide the string text1 into two parts, divide the length by 2 using true division and use string slicing. Perform the string concatenation of text2 in the middle of text1. Store the new string in variable named as data and return the data variable
def middle(text1, text2):
data = text1[:len(text1) // 2] + text2 + text1[(len(text1) // 2):]
return data
In the main function take two strings string1 and string2 ask the user to enter two strings using input() function call. Then call the function middle() by passing two variables string1 and string2 as input to the python program, store the result in result_string. Use a print statement to print the resulting string.
string1 = input("Enter First String : ")
string2 = input("Enter Second String : ")
result_string = middle(string1, string2)
print(result_string)
Code
==========
def middle(text1, text2):
data = text1[:len(text1) // 2] + text2 + text1[(len(text1) // 2):]
return data
string1 = input("Enter First String : ")
string2 = input("Enter Second String : ")
result_string = middle(string1, string2)
print(result_string)
Output
=============
Enter First String : hello
Enter Second String : ***
he***llo
Output
=============
Enter First String : helloo
Enter Second String : ***
hel***loo
Conclusion
=================
Execute the above python program by providing the two input strings, note down the results.
Comment down below if you have any suggestions regarding the above python program.
0 Comments