+ 5

could someone tell me why the output of the code below is.......

var="hello baby" a=var[::3] print(a) Outputs : hlby why did it print these 4 chars & whats the job of the :: here? Thank you

12th Nov 2018, 8:37 PM
RiGeL
RiGeL - avatar
4 ответов
+ 16
a=var[::3] is the same as a=var[0:len(var):3] which will get every 3rd character from the 1st (index=0) to the last character (index=len(var)-1) of the string var The :: are there for slicing lists or strings in python. https://www.sololearn.com/learn/Python/2453/
12th Nov 2018, 8:49 PM
Uni
Uni - avatar
+ 7
the :: is like the coordinates for the list. x:y:z x is the starting index. y is the ending index. and z is the step, or in other words, its how many places in the list are skipped .
12th Nov 2018, 8:50 PM
LONGTIE👔
LONGTIE👔 - avatar
+ 1
if the colon is between number inside square bracket then it means, element is being sliced. e.g.: var = 'hello baby' print(var[0:5]) # will print "hello" bcoz var[0]='h' var[1]='e' var[2]='l' var[3]='l' var[4]='o' Pls note range will stop one point before from the end number. double [::] colon means the range is from 0 to end number after double colon tells this slicing to skip as many number as mentioned. Hope you would understand now.
13th Nov 2018, 8:42 AM
Solmon Raja
Solmon Raja - avatar
+ 1
you are slicing from beginning of the list to the end with a step of 3. So the code selects the index 0,2,5,8 which returns hlby
14th Nov 2018, 7:57 AM
Tamara
Tamara - avatar