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 the end is the starting position and ending position and step are the no. of steps taken each time. The 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] >>>print(s[3:14]) com to Pyt #Here Index of t is 13 #s[:j] starts at s,therefore s[:j]==s[0:j] >>>print(s[:12]) Welcome to P #s[i:] ends at len(s)-1,therefore s[i:]==s[i:len(s)-1] >>>print(s[5:]) me to Python #If we also give steps then it will jump those no. of characters during printing. >>>print(s[::2]) Wloet yhn #If negative integer is used in place of step then python will print the string from right to left side. >>>print(s[::-3]) nt oe
Both positive as well as negative indices can be used in slicing.
6. Reversing String
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.
>>>s="Hello!" >>>print(s[::-1]) !olleH