filmov
tv
slicing in python|python tutorial for beginners 6 [2020]

Показать описание
-----------------------------------------------------------------------------------------
slicing in python|python tutorial for beginners 6 [2020]
Every element has a unique index in a sequence.
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
We can use index to access the element of a sequence.
s= "python"
print(s[2]) # the third element
print(s[-2]) # the second element from last
slicing
Gives access to a specified range of sequence’s elements. the Syntax is:
sequence [start:stop[:step]]
start Optional. Starting index of the slice. Defaults to 0.
stop Optional. The last index of the slice or the number of items to get. Defaults to len(sequence).
step Optional. Extended slice syntax. Step value of the slice. Defaults to 1.
"hwdong"[0:2]
"hwdong"[0:4:2]
"hwdong"[0::2] #equal to "hwdong"[0:len("hwdong"):2]
"hwdong"[0:len("hwdong"):2]
"hwdong"[1:]
"hwdong"[:3]
"hwdong"[1:3]
"hwdong"[1:3:]
"hwdong"[::2]
"hwdong"[::]
"hwdong"[:]
Negative step argument can be used to reverse the sequence:
"hwdong"[::-1]
"hwdong"[:0:-1]
"hwdong"[3:0:-1]
"hwdong"[0:3:-1]
delete sub-sequece by slicing
For mutable sequece,you can delete sub-sequece by slicing:
a = [1,2,3,4,5,6]
a[1:4]
a[1:4] = []
print(a)
a = (1,2,3,4,5,6)
a[1:4] = ()
slicing in python|python tutorial for beginners 6 [2020]
Every element has a unique index in a sequence.
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
We can use index to access the element of a sequence.
s= "python"
print(s[2]) # the third element
print(s[-2]) # the second element from last
slicing
Gives access to a specified range of sequence’s elements. the Syntax is:
sequence [start:stop[:step]]
start Optional. Starting index of the slice. Defaults to 0.
stop Optional. The last index of the slice or the number of items to get. Defaults to len(sequence).
step Optional. Extended slice syntax. Step value of the slice. Defaults to 1.
"hwdong"[0:2]
"hwdong"[0:4:2]
"hwdong"[0::2] #equal to "hwdong"[0:len("hwdong"):2]
"hwdong"[0:len("hwdong"):2]
"hwdong"[1:]
"hwdong"[:3]
"hwdong"[1:3]
"hwdong"[1:3:]
"hwdong"[::2]
"hwdong"[::]
"hwdong"[:]
Negative step argument can be used to reverse the sequence:
"hwdong"[::-1]
"hwdong"[:0:-1]
"hwdong"[3:0:-1]
"hwdong"[0:3:-1]
delete sub-sequece by slicing
For mutable sequece,you can delete sub-sequece by slicing:
a = [1,2,3,4,5,6]
a[1:4]
a[1:4] = []
print(a)
a = (1,2,3,4,5,6)
a[1:4] = ()