[SOLVED] Given a string, S , print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line

Issue

I know it can be simply done through string slicing but i want to know where is my logic or code is going wrong. Please Help!

S=input()
string=""
string2=""
list1=[]
list1[:0]=S
for i in list1:
    if(i%2==0):
        string=string+list1[i]
    else:
        string2=string2+list1[i]
print(string," ",string2)

Here’s my code. Firstly i stored each character of string in the list and went by accessing the odd even index of the list.
But i’m getting this error

if(i%2==0):
TypeError: not all arguments converted during string formatting

Solution

You are iterating over characters, not indices, so your modulo is incorrect, equivalent to:

i = "a"
"a" % 2 == 0

You want to use enumerate

for idx, letter in enumerate(list1):
    if(idx%2 == 0)
         string += letter

Answered By – Sayse

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

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