Print Even and Odd Index Characters of a String – Python
Last Updated :
27 Jul, 2023
Given a string, our task is to print odd and even characters of a string in Python.
Example
Input: Geeksforgeeks
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 = 'Geekforgeeks'
even_characters = []
odd_characters = []
for i in range ( len (given_str)):
if i % 2 = = 0 :
even_characters.append(given_str[i])
else :
odd_characters.append(given_str[i])
print ( 'Odd characters: {}' . format (odd_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 = "GeEksforgeeks"
print ( "Even Characters:" , given_str[:: 2 ])
print ( "Odd Characters:" , given_str[ 1 :: 2 ])
|
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 = "Geeksforgeeks"
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 ):
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 = "Geeksforgeeks!"
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 !
Share your thoughts in the comments
Please Login to comment...