YoungDanEn
YoungDanEn

Reputation: 27

create a new string with only the odd indexes of string

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)

Upvotes: 0

Views: 3922

Answers (4)

Arghyadeep Giri
Arghyadeep Giri

Reputation: 9

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)

Upvotes: 0

Abhishek Dey
Abhishek Dey

Reputation: 1639

You can also try something like:

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

Upvotes: 0

TigerhawkT3
TigerhawkT3

Reputation: 49330

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

def odd_string(data):
    return data[1::2]

Upvotes: 7

Ambidextrous
Ambidextrous

Reputation: 820

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

Upvotes: 1

Related Questions