Table of Contents
Introduction
The task is to add the string in the middle of the given phrase.
Approach
- Split the given string into list and find the middle position.
- Append the word to be added using slicing
- Join the strings based on space delimiter
Program
ip_str = input("Enter the phrase : ") word = input("Enter the string to be inserted in the middle : ") #Splitting string and finding md position str_split = ip_str.split() mid = len(str_split)//2 #Append output = str_split[:mid] + [word] + str_split[mid:] output = ' '.join(output) print("Output string is : "+str(output))
Output
Explanation
In the above program, we have split the given phrase into list using split() function. The length of the list divided by 2 will give the middle position. Now we have added the word in the list in pattern: strings before middle position + to be added string + strings after middle position. The output list is then joined using space delimiter and then printed on the screen.
0 Comments