Navya Thakur
Navya Thakur

Reputation: 39

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

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

Upvotes: 1

Views: 1595

Answers (2)

Sayse
Sayse

Reputation: 43320

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

Upvotes: 1

BrokenBenchmark
BrokenBenchmark

Reputation: 19253

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.)

S = input()
even_index_characters = ""
odd_index_characters = ""

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

print(f"{even_index_characters} {odd_index_characters}")

Upvotes: 1

Related Questions