How to print the even-indexed and odd-indexed characters of strings?

Task at hand:

Given a string, S, of length N that is indexed from 0 to N-1, print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line.

The test cases are written such that The first line contains an integer, N (the number of test cases). Each line i of the N subsequent lines contain a String.

Here is my code:

N = int(raw_input())

for i in range(0,N):
    string = raw_input()

evenlist = []
oddlist = []

for item, char in enumerate(strg):
    if item % 2 == 0:
        evenlist.append(char)
    else:
        oddlist.append(char)

print ''.join(evenlist), ''.join(oddlist)

Sample run:

The first input is:
2
Hacker
Rank

Expected output is:
Hce akr
Rn ak

But I get:

HceRn akrak

Here is a link to the assignment that might explain the question better.

Answer

Simpler way to achieve this is via using string slicing:

>>> my_str = 'Hacker'
>>> '{} {}'.format(my_str[::2], my_str[1::2])
'Hce akr'

Hence, your entire code could be written as:

for _ in range(int(raw_input())):
    my_str = raw_input()
    print '{} {}'.format(my_str[::2], my_str[1::2])

Leave a Reply

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