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
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.