Program to add characters in the middle using Python

Introduction

The task is to add the string in the middle of the given phrase.

Program to add characters in the middle using Python

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

Program to add characters in the middle 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.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.