1
votes

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
2

2 Answers

0
votes

You are iterating over characters, not indices, you want to use enumerate

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

You don't need to use an intermediate list: just iterate over the input string directly. You also need to use for i in range(len(original)) rather than for i in original, because you need to keep track of whether a given character is at an odd or an even index. (I've gone ahead and renamed some of the variables for readability.)

original = input()
even_index_characters = ""
odd_index_characters = ""

for i in range(len(original)):
    if i % 2 == 0:
        even_index_characters += original[i]
    else:
        odd_index_characters += original[i]
print(even_index_characters)
print(odd_index_characters)