Slicing is a Python attitude that enables accessing parts of data from the given sequence like list, tuples etc. A slice object is created based on a set of indices. Slicing starts anywhere from list and stop anywhere as your requirement. When we create the slice then we define the start, stop and step indices. In other word we can say that slice is the piece of string.
Syntax: strobj [start: stop: step]
Start: Starting index where the slicing of object starts.
Stop: Ending index where the slicing of the object ends.
Step: Increment value
Step value can be positive (+) or negative (-) but cannot be zero.
If Step value is positive then it should be from left to right forward direction. Range it 0 to end-1.
If step value is negative then it should be from right to left backward direction. Range it -1 to end+1
Slice () function returns a slice object used to slice a sequence in the given indices.
For Example:
Using List Object:
N= [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
Num=N [3:7]
print(Num)
In our example it start from value 20 and stop is 35, here we are passing positive index then it should be from left to right forward direction .
Output:
[20, 25, 30, 35]
Another example:
num= [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
print(num[:7])
print(num[4:])
print(num[::]
Output:
[5, 10, 15, 20, 25, 30, 35]
[25, 30, 35, 40, 45, 50]
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
Indexing:
Python allows us to rescue individual elements of a sequence by specifying its index of that element. It is the integer that uniquely identifies that member’s position in the sequence. Python uses a zero-based indexing system, sense that the first element in a sequence is placed at position 0 and it also permits the use of negative integers to count from the end of the sequence.
For Example:
We take a string “PROGRAMMING”
Here the first row of numbers gives the position of the indices 0 to 10 in the string whereas the second row gives the corresponding negative indices -1 to -11.
Kommentare