+ 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
4 Réponses
+ 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/
+ 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 .
+ 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.
+ 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