Python program for printing odd and even letters of a string

Hello friends in this tutorial, we will learn how to print odd and even letters of a given string and write the code for it in Python.

Check how to print odd and even letters of a string in Python

Let’s first understand the concept behind it.

Condition 1: If the number is divisible by 2 and leaves no remainder, this means that the number is even.
Python syntax for even: if number % 2==0:

Condition 2: If the number is not divisible by 2, this means that the number is odd.

Now from this, we can conclude that odd places start with 1,3,5,7,8…so on. Whereas even places start with 2,4,6,8,10…so on.

For example, we have a string “CodeSpeedy” so its odd letters would be C,d, S,e,d, which are at odd places and even letters would be o,e,p,e,y as they are at even places.

Now let’s see how we can implement it in python and have a look at the code given below.

Program:

number_of_strings = int(input("Enter no of strings: "))
for line in range(number_of_strings):
    string = input("Enter string: ")
    even_string = ""
    odd_string = ""
    for i in range(len(string)):
        if i%2==0:
            even_string = even_string  + string[i]
        else:
            odd_string = odd_string + string[i]
    print(even_string,odd_string)

In the above code firstly we are taking input from the user for the number of strings. Then we put a “for” loop to print odd and even letters of a string.

Then there is another “for” loop inside it which is using if and else statements to find out which letter belongs to which place. To find out whether it is odd or even.  All the odd places letter will be added in “odd_string” and same way all the even places letter will be added in “even_string”.

Then lastly we print both the “odd_string” and “even_string” together as you can see in the output given below.

Output 1:

Enter no of strings: 1
Enter string: CodeSpeedy
CdSed oepey

Output 2:

Enter no of strings: 2
Enter string: Code
Cd oe
Enter string: Speedy
Sed pey

As you can see the results came out as expected. I tried to implement it in the simplest way possible. I hope you like it. If you have any doubts then please comment below.
Also read: Python string startswith() Method

 

Leave a Reply

Your email address will not be published. Required fields are marked *