Python program to remove characters from odd or even index of a string

Python 3 program to remove characters from odd or even index from a string :

In this example, we will write one program in Python 3 to remove all characters positioned on Even or Odd . We will ask the user if he wants to remove odd or even indexed characters. Following algorithm we are going to use in this program :

Algorithm to remove odd or even index character from a string :

1. First take the string from the user.
2. Create one variable empty string to store the output.
3. Ask the user if he wants to remove odd or even positioned characters from the string
4. Using a loop, iterate through the string. Add the character on even or odd position to the output string.
5. Print the output string.

Python 3 Program :

input_string = input("Enter a string : ")

output_string = ""

oddOrEven = int(input("Enter '1' if you want to remove odd positioned characters , '2' for even positioned characters : "))

if oddOrEven ==1 :
	print ("String after removing characters on odd position : ")
	for i in range(len(input_string)):
		if i%2 != 0:
			output_string = output_string + input_string[i]

elif oddOrEven == 2 :
	print ("String after removing characters on even position : ")
	for i in range(len(input_string)):
		if i%2 == 0:
			output_string = output_string + input_string[i]

print (output_string)

Sample Output :

Enter a string : Hello
Enter '1' if you want to remove odd positioned characters , '2' for even positioned characters : 2
String after removing characters on even position :
Hlo

Enter a string : Hello
Enter '1' if you want to remove odd positioned characters , '2' for even positioned characters : 1
String after removing characters on odd position :
el

In the above example, we are removing characters from ‘Hello’ . Position of each characters are :

H - 1
e - 2
l - 3
l - 4
o - 5

So, the string after removing odd index characters is : el . And the string after removing even index characters is : Hlo

Leave a Reply