Python program to Remove Odd Characters in a String

Write a Python program to Remove Odd Characters in a String with a practical example.

Python Program to Remove Odd Characters in a String Example

This python program allows the user to enter a string. First, we used For Loop to iterate each character in a String. Inside the For Loop, we used the Python If statement to check whether the index value is divisible by true or not. If True, add the character (index position – 1) to the Python String str2.

str1 = input("Please Enter your Own String : ")

str2 = ''

for i in range(1, len(str1) + 1):
if(i % 2 == 0):
str2 = str2 + str1[i - 1]

print("Original String : ", str1)
print("Final String : ", str2)

Remove the odd characters in a string using for loop output

Please Enter your Own String : Tutorial Gateway
Original String :   Tutorial Gateway
Final String :      uoilGtwy

Python Program to Delete Odd Characters in a String Example 2

This program to removes odd characters is the same as above. However, we just replaced the Python For Loop in Python code with Python While Loop.

str1 = input("Please Enter your Own String : ")

str2 = ''
i = 1
while(i <= len(str1)):
if(i % 2 == 0):
str2 = str2 + str1[i - 1]
i = i + 1

print("Original String : ", str1)
print("Final String : ", str2)

Removing the odd characters in a string using a while loop output

Please Enter your Own String : Python Programs
Original String :   Python Programs
Final String :      yhnPorm

Python Program to Delete Odd Characters in a String Example 3

This removes odd characters program is the same as the first example. But, this time, we used Python Functions to separate the logic. For more examples, refer to the Python Basic Programs.

def RemoveOddCharString(str1):
str2 = ''

for i in range(1, len(str1) + 1):
if(i % 2 == 0):
str2 = str2 + str1[i - 1]
return str2

string = input("Please Enter your Own String : ")
print("Original String : ", string)
print("Final String : ", RemoveOddCharString(string))
Python program to Remove Odd Characters in a String

Also Read