Reputation: 27
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
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
Reputation: 1639
You can also try something like:
newlist = list(range(10))
print newlist[1::2]
Upvotes: 0
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
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