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

Similar Reads

Using  Brute-Force Approach to get even and odd index characters

First, create two separate lists for even and odd characters. Iterate through the given string and then check if the character index is even or odd. Even numbers are always divisible by 2 and odd ones are not. Insert the characters in the created lists and display the lists....

Using Slicing to get even and odd index characters of a string in python

...

Using List Comprehension to get even and odd index characters of a string in python

To understand the concept of string slicing in detail. Refer here...

Print Even and Odd Index Characters of a String using recursion

...