Slicing in Python

Python provides a very useful feature to access a specific slice from whole string. Provide the starting and ending index of string and you will get your slice.

variable_name [starting_index : ending_index]

lets create a variable called prog with following value

## declare a variable prog
prog = "I love java"

As you have already learnt in Strings in python that string declaration in memory is as follow.  

0 1 2 3 4 5 6 7 8 9 10
I l o v e j a v a

When a string variable is stored in memory, every single character is assigned an individual memory address. Lets say you want to access the slice including 2nd, 3rd, 4th and 5th index. 

## get slice from 2nd index till 5th index, index 6 is not included
myslice = prog[2:6]


and output is love. As you have already noticed that ending_index is not included in slice, this is how Python works.

Python provides number of options to get slice from string. For example if you do not mention the starting_index of the slice, so the by default value will be 0 and output of the following example will be I love

lang = "I love java"

## no starting index
myslice = lang[ : 6]

In the same case if the ending_index is not provided then the by default value will be last index of the string and this time last index will be included in slice.

lang = "I love java"

## no ending_index
myslice = lang[7 : ]

This example will print java instead of jav.

You can also fetch a slice and replace with your required string. 

lang = "I love java"

myslice = lang[ : 7] + "python" 

and the output is i love python because lang[0:7] will take a slice of “I love ” and then combine it with other string “Python”. Check another example in which bluebox is turned into bluetooth. 

tech = "bluebox"
myslice = tech[0:4]+"tooth"

Slicing also works with normal list or arrays. Create an integer array and perform same slicing experiments.

myarray = [2,3,5,6,8,10,12,15]


You can also provides an increment in slicing. See following example, 

myarray = [2,3,5,6,8,10,12,15]
print(myarray[0: 7: 3])

staring_index is 0, ending_index is 7 and there is an extra variable which is 3. Starting from 0 index, every third value in this range will be printed.

Output [2, 6, 12]. You can use this increment in reverse order as well.

## ending point, starting point, increment of -1
print(myarray[-1: -len(myarray) -1: -1])

## in simple form
print(myarray[: : -1])