0

I have to do the following thing"

Write a function that takes a string as input and returns a string composed of only the odd indexes of the string. Note: enumerate() is not available.

now the code I can come up with is

def odd_string(data):
    result = ""
    for i in (data):
    return data[0],data[2],data[4]

print (odd_string("hello"))

how do i actually append these values to a string and how do I make it so that each odd number will be added(without having to write them all out)

2
  • I suppose you're not allowed to use stride indexing, either? Commented Apr 30, 2015 at 2:17
  • That is a bafflingly obtuse assignment. I mean, a string of length n has n//2 odd indices, so you could just do ''.join(map(str, range(1, len(s), 2))). That would give you a string composed of the indices. Surely that's not what the question means, but it is what it asked for. Commented Apr 30, 2015 at 2:18

4 Answers 4

7

Stride indexing (you're probably familiar with it from range()) works well here.

def odd_string(data):
    return data[1::2]
Sign up to request clarification or add additional context in comments.

3 Comments

My guess is that his attempted code is a misinterpretation of the assignment - 0, 2, and 4 are clearly not odd indices.
I originally posted an answer, and then realized that I posted this one almost word for word (I hadn't read it yet). "There should be one -- and preferably only one -- obvious way to do it." :-D One comment: The OP said that he needed the odd indices, but his example showed the even indices (0, 2, 4). If he really does need the even (not odd), the return statement should be return data[::2].
Ah - much better solution than mine.
1

Something like this maybe?

def odd_string(data):
result = ''
for c in range(0, len(data)):
    if (c % 2 == 1):
        result += data[c] 
return result

2 Comments

you used the opposite definition of odd from OP. I'm would have picked %2==1 as well, but the assignment itself needs clarification.
By the way, you can replace (c % 2 == 1) with c%2, as a truthy value.
0

You can also try something like:

newlist = list(range(10))
print newlist[1::2]

Comments

0
while i<T:
temp =input()
even=""
odd=""
j=0
k=1
while j<len(temp):
    even = even+temp[j]
    j+=2
while k<len(temp):
    odd = odd+temp[k]
    k+=2
i+=1
print (even,odd)

2 Comments

This is very inefficient compared to stride. See the accepted answer.
Absolutely. Thanks for letting me know. I tried that, but eventually, it was giving me the even numbers. I did not bother to play around with it and also missed the comment section at stride's answer. So much to learn in python :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.