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
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.
Python3
given_str = 'GeekforBeginner' # given input string even_characters = [] # For storing even characters odd_characters = [] # For storing odd characters for i in range ( len (given_str)): if i % 2 = = 0 : # check if the index is even even_characters.append(given_str[i]) else : odd_characters.append(given_str[i]) # print the odd characters print ( 'Odd characters: {}' . format (odd_characters)) # print the even characters print ( 'Even characters: {}' . format (even_characters)) |
Output:
Gesoges ekfrek
Using Slicing to get even and odd index characters of a string in python
To understand the concept of string slicing in detail. Refer here
Python3
given_str = "w3wiki" print ( "Even Characters:" , given_str[:: 2 ]) # Characters at even index print ( "Odd Characters:" , given_str[ 1 :: 2 ]) # Characters at odd index |
Output:
Gesoges ekfrek
Using List Comprehension to get even and odd index characters of a string in python
List comprehension provides a shorter index to create a new list using the given list. For a deeper understanding, refer here
Python3
list1 = "w3wiki" list2 = [x for ind, x in enumerate (list1) if ind % 2 = = 0 ] list3 = [x for ind, x in enumerate (list1) if ind % 2 ! = 0 ] print (list2) print (list3) |
Output:
['G', 'e', 's', 'o', 'g', 'e', 's']
['e', 'k', 'f', 'r', 'e', 'k']
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 !
Contact Us