# Python Program to Remove the Characters of Odd Index Values in a String

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

When it is required to remove characters from odd indices of a string, a method is defined that takes the string as parameter.

Below is the demonstration of the same −

## Example

Live Demo

def remove_odd_index_characters(my_str):
new_string = ""
i = 0
while i < len(my_str):
if (i % 2 == 1):
i+= 1
continue

new_string += my_str[i]
i+= 1
return new_string

if __name__ == '__main__':
my_string = "Hi there Will"

my_string = remove_odd_index_characters(my_string)
print("Characters from odd index have been removed")
print("The remaining characters are : ")
print(my_string)

## Output

Characters from odd index have been removed
The remaining characters are :
H hr il

## Explanation

• A method named ‘remove_odd_index_characters’ is defined, that takes a string as parameter.

• An empty string is created.

• The string is iterated over, and the index of every element is divided by 2.

• If the remainder is not 0, then it is considered as an odd index, and it is deleted.

• In the main method, the method is called, and the string is defined.

• This string is passed as a parameter to the method.

• The output is displayed on the console.

Updated on 16-Apr-2021 12:22:23