Python Program to Remove Odd Indexed Characters in a string

This is a Python Program to remove the characters of odd index values in a string.

Problem Description

The program takes a string and removes the characters of odd index values in the string.

Problem Solution

1. Take a string from the user and store it in a variable.
2. Pass the string as an argument to a function.
3. In the function, initialize a variable to an empty character.
4. Use a for loop to traverse through the string.
5. Use an if statement to check if the index of the string is odd or even.
6. If the index is odd, append the no character to the string.
7. Then print the modified string.
8. Exit.

Program/Source Code

Here is source code of the Python Program to remove the characters of odd index values in a string. The program output is also shown below.

def modify(string):  
  final = ""   
  for i in range(len(string)):  
    if i % 2 == 0:  
      final = final + string[i]  
  return final
string=raw_input("Enter string:")
print("Modified string is:")
print(modify(string))
Program Explanation

1. User must enter a string and store it in a variable.
2. This string is passed as an argument to a function.
3. In the function, a variable is initialized with an empty character.
4. A for loop is used to traverse through the string.
5. An if statement checks if the index of the string is odd or even.
6. If the index is odd, the empty character variable is appended to the string thus indirectly removing the character.
7. Finally the modified string is printed.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Enter string:hello
Modified string is:
hlo
 
Case 2:
Enter string:checking
Modified string is:
cekn

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.