+ 2

Can we do this range option on string?

I tried but failed... I wrote the code like.... A="dragon" A=list(range(1, 7, 2))Print(A)EXPECTED OUTPUT-['d', 'a', 'o']Actual output -[1, 3, 5]

28th Jul 2016, 11:26 AM
samridhi - avatar
3 Answers
+ 5
Your question is answered... But now let's see why you got 1,3, 5 for your code... ------------- #you initialized A A="dragon" #you reinitialized A with ranges... Previous value gets overwritten A=list(range(1,7,2)) #Now, A =[1,3,5] since, from 1 till 7(excluding 7) with interval of 2 print(A) #that's why you got 1, 3, 5 ------------- #Alterntive Solution... Should work.. But not working.. -,- A="dragon" for i in range(0,6,2): A[i/2]=A[i] del(A[3],A[4],A[5]) print(A) ## Alternative Solution 2, Works perfectly A="dragon" A=A[::2] #Using slice like said by Red Ant print(A) #Output : dao ##Alternate solution 3, works fine A=["d","r","a","g","o","n"] B=[] for i in range(0,6,2): B.append(A[i]) print(B) # output : ["d","a","o"]
28th Jul 2016, 3:51 PM
Prashant Shahi
Prashant Shahi - avatar
+ 3
If you specifically want to use range, there is a way. But you will have to create another list. a="dragon" b=[" "]*3 a=list(a) b=list(b) j=0 for i in range(0,6,2): b[j]=a[i] j+=1 print (b) If you don't want to use another variable then directly print(a,end=" ") inside Loop, but then you won't get a list.
28th Jul 2016, 1:28 PM
Nishant Chhetri
Nishant Chhetri - avatar
+ 1
you can use list slices ( lesson More Types/List slices ) on the strings to achieve something like that. so to get your desired output you can use: A[0::2] which basically means take first character, then every other till the end of the string.
28th Jul 2016, 11:47 AM
RedAnt - avatar