Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

slice

Concept:
# can be used with indexed containers like str,list,tuple (not deque though).
# This concept of start end and step is same in range() function used in loop.
# The key point to remember is that the :stop value represents the
# first value that is not in the selected slice.

s[start:end:step] or s[start:stop:step] ,
If step is positive, the defaults for start is 0 and end is len(s),
but defaults are only considered when no value is explicitly written
like a[:3] here since step is 1 aka it is +ve -> start = 0.
Else step is -ve, then defaults for start is 
len(s)-1 or -1 and for end it is -(len(s)+1).

# step is the number of steps of jumping between 2 objects/chr/int. 
if step>0 :
    start index necessarily needs to be on left of end/stop.
    if start is right of end -> slicing returns '' empty str.
elif step<0:
    start index necessarily needs to be on right of end/stop.
    if start is left of end -> slicing returns '' empty str.
    
The key point to remember is that the :stop value represents the
first value that is not in the selected slice.
So, the difference between stop and start is the number of elements 
selected (if step is 1, the default).
# if not explicitly written => take step as 1.
s[start:stop]  # items start through stop-1
s[start:]      # items start through the rest of the array
s[:stop]       # items from the beginning through stop-1
s[:]           # a copy of the whole array

The other feature is that start or stop may be a negative number,
which means it counts from the end of the array instead of the beginning. 
s[-1]    # last item in the array
s[-2:]   # last two items in the array
s[:-2]   # everything except the last two items

Similarly, step may be a negative number:
s[::-1]    # all items in the array, reversed
s[1::-1]   # the first two items, reversed
s[:-3:-1]  # the last two items, reversed
s[-3::-1]  # everything except the last two items, reversed


Note: if you write an out of bound index in place of start or end then 
one of 2 last indexes(close to written out of bound index) is taken.
ex based on above note:
s='abcd'
print(s[:22])
//abcd
examples:
s="dbdhdhndnbdd"
print(s[2:6:2])
//prints dd , since z>0 ->start should be left of end else returns ''
//since both start and end are explicityly written no default value assumed
//start =2 & end=6(1st value to not get included) => no '' is returned
//substring from 2 to 5 is dhdh & 2 means pick d,skip h,then pick d.
s="djdjcjfd"
print(s[::-3])
//prints dcj, step=-3 means start should be right of end
//here start is -1 and end is -(len(s)+1) -> substring is dfjcjdjd from start
//to end & in steps of 3->pick d,skip f&j,pick c,skip j&d,then pick j,skip d.
# now below 2 must be a piece of cake.
s="abcdef"
print(s[5:-len(s):-1])
//prints fedcb
s="abcdef"
print(s[1:len(s):-1])
//prints ""
Source by developer.mozilla.org #
 
PREVIOUS NEXT
Tagged: #slice
ADD COMMENT
Topic
Name
4+9 =