Print Even and Odd Index Characters of a String using recursion
To print the even and odd index characters of a string using recursion in Python, we can define a recursive function that traverses the string and prints characters at even and odd indices. Here’s the Python program to achieve this:
Python
def print_even_odd_chars(string, index = 0 , even = True ): # Recursive function to print even and # odd index characters of the string if index > = len (string): return if even and index % 2 = = 0 : print (string[index], end = ' ' ) elif not even and index % 2 ! = 0 : print (string[index], end = ' ' ) print_even_odd_chars(string, index + 1 , even) if __name__ = = "__main__" : input_string = "w3wiki!" print ( "Even Index Characters:" ) print_even_odd_chars(input_string, even = True ) print ( "\nOdd Index Characters:" ) print_even_odd_chars(input_string, even = False ) |
Output:
Even Index Characters:
G e s o g e s
Odd Index Characters:
e k f r e k !
Print Even and Odd Index Characters of a String – Python
Given a string, our task is to print odd and even characters of a string in Python.
Example
Input: w3wiki
Output: Gesoges ekfrek