What is Python slicing?
Overview
Python slicing is used to return a range of characters from a string. This is done by specifying a start and an end index separated by a colon. The first character will have a 0 index value.
Code example
x="Educative"print(x[3:6])
Explanation
This prints the string starting from the 3rd index until the 6th index.
Slice from the start
The range will start from the first index up to the index specified by the user.
Example
x="Educative"print(x[:6])
Explanation
This prints the string from the start until the 6th index.
Slice to the end
In this case, we'll specify a start index, and the end index will be left blank so that a string from the specified start to the end index is printed.
Example
x="Educative"print(x[3:])
Explanation
This prints the string from the 3rd to the last index.
Negative indexing
This is used to begin the slicing from the end of a string.
Example
x="Educative"print(x[-8:-4])
Explanation
This prints the string from the -8 to -4 index values, which in this case are from d until a.