Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading