Write A Python Function To Replace The Middle String Characters By 0

In this article let's learn how to add 0 in the middle of the given string.

Consider two cases

  • string is even length “abcd” add the “0” in the middle it will appear something like this “ab0d”
  • String is odd length “abc” add the “0” in the middle so that it will appear like this “a0c”

 

Write A Python Function To Replace The Middle String Characters By 0




Write A Python Function To Replace The Middle String Characters By 0

Define a python function add_zero_mid() and pass the input string as function argument. Divide the string into two parts using string slicing.



First Part

        text[:len(text) // 2]



Second Part 

        text[(len(text) // 2) + 1:]
        Add 1 to length to take out the middle element.


Add a new “0” in the middle of the string and get a new string and store it into a new variable named data and return the data.


def add_zero_mid(text):
   data = text[:len(text) // 2] + "0" + text[(len(text) // 2) + 1:]
   return data

 




In the main program take a variable named input_string and ask the user to enter a string, store it in input_string. Call the above function to add “0” to the middle of the string and store the return value in variable output_string.


Using the print() function call to print the string with “0” in the middle.

input_string = input("Enter a String : ")
result_string = add_zero_mid(input_string)
print(result_string)




Python Working Code
==========================

def add_zero_mid(text):
   data = text[:len(text) // 2] + "0" + text[(len(text) // 2) + 1:]
   return data


input_string = input("Enter a String : ")
result_string = add_zero_mid(input_string)
print(result_string)





OUTPUT
===============

Enter a String : hello
he0lo



OUTPUT
==============

Enter a String : abc
a0c



OUTPUT
===============

Enter a String : abcd
ab0d



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

Execute the above program by providing the odd length and even length strings as input. Comment down below if you have any suggestions regarding the above program.



Post a Comment

0 Comments