slice function in python code example

Example 1: python slice an array

a[start:stop]  # items start through stop-1
a[start:]      # items start through the rest of the array
a[:stop]       # items from the beginning through stop-1
a[:]           # a copy of the whole array
Example:
>>> a = [1, 2, 3, 4, 5, 6, 7, 8]
>>> a[1:4]
[2, 3, 4]

Example 2: slicing in python

word = "Example"

# Obtain the first 3 characters of "Example"
# E x a m p l e
# 0 1 2 3 4 5 6
# First 3 characters = "Exa"
sliced_word = word[:3] # Gives you "Exa"

# Everything after character #3 = "mple"
second_sliced_word = word[3:] # Gives you "mple"

Example 3: python slice

# array[start:stop:step]

# start = include everything STARTING AT this idx (inclusive)
# stop = include everything BEFORE this idx (exclusive)
# step = (can be ommitted) difference between each idx in the sequence

arr = ['a', 'b', 'c', 'd', 'e']

arr[2:] => ['c', 'd', 'e']

arr[:4] => ['a', 'b', 'c', 'd']

arr[2:4] => ['c', 'd']

arr[0:5:2] => ['a', 'c', 'e']

arr[:] => makes copy of arr

Example 4: python3 slice

# array[start:stop:step]

# start = include everything STARTING AT this idx (inclusive)
# stop = include everything BEFORE this idx (exclusive)
# step = (can be committed) difference between each idx in the sequence

arr = ['a', 'b', 'c', 'd', 'e']

arr[2:] => ['c', 'd', 'e']

arr[:4] => ['a', 'b', 'c', 'd']

arr[2:4] => ['c', 'd']

arr[0:5:2] => ['a', 'c', 'e']

arr[:] => makes copy of arr

Example 5: python slice operator

string = 'string_text'

beginning = 0 # at what index the slice should start.
end = len(string) # at what index the slice should end.
step = 1 # how many characters the slice should go forward after each letter

new_string = string[beginning:end:step]

# some examples
a = 0
b = 3
c = 1

new_string = string[a:b:c] # will give you: str
# ____________________________________________
a = 2
b = len(string) - 2
c = 1

new_string = string[a:b:c] # will give you: ring_te

Example 6: is : and :: the same in python slice

a[::-1]    # all items in the array, reversed
a[1::-1]   # the first two items, reversed
a[:-3:-1]  # the last two items, reversed
a[-3::-1]  # everything except the last two items, reversed

Tags:

Misc Example