A very important thing we can do with python strings is to extract a part of the string.
It can be done in python by making a slice.It is a segment of a string.It is used to get a sub-string from a starting point(say,i) to an ending point(say,j). It is used to retrieve a subset of the string.It can be done using a slice operator(two indices in square brackets separated by a colon([:])).
Here start and end is the starting position and ending position and step are the no. of steps taken each time.The by default value of start is the starting position(index 0) and the ending position is the length of string.Steps are taken as 1 by default
*Here end is excluded from the range.
#This is an example of string slicing
s="Welcome to Python"
#s[i:j] starts from s[i] and go till s[j-1]
com to Pyt #Here Index of t is 13
#s[:j] starts at s,therefore s[:j]==s[0:j]
Welcome to P
#s[i:] ends at len(s)-1,therefore s[i:]==s[i:len(s)-1]
me to Python
#If we also give steps then it will jump those no. of characters during printing.
#If negative integer is used in place of step then python will print the string from right to left side.
Both positive as well as negative indices can be used in slicing.
As told above if we don’t give ‘start’ and ‘end’ then python will take whole string into consideration.At the same time if we declare steps as -1 then it will print string in the reverse order as shown.