The prototype of the slice operator in Python is
[Start:stop:step]
That is: [Start index: End index: Step value]
Start index: Same as other languages, starting from 0. Sequence from left to right, index of first value is 0, last one is-1
End index: The slice operator is taken to the index and does not contain the value of the index.
Step value: The default is one after the other, if it is 2, it means to take one operation. When the step value is positive, it is taken from left to right and, if negative, from right to left. The step value cannot be 0
Printstr[0:3]#截取第一位到第三位的字符Printstr[:]#截取字符串的全部字符Printstr[6:]#截取第七个字符到结尾Printstr[:-3]#截取从头开始到倒数第三个字符之前Printstr[2]#截取第三个字符Printstr[-1]#截取倒数第一个字符Printstr[::-1]#创造一个与原字符串顺序相反的字符串Printstr[-3:< Span class= "Hljs-number" >-1] #截取倒数第三位与倒数第一位之前的字符 print str[- 3: ] #截取倒数第三位到结尾 print str[:-5:-3] #逆序截取
eg
Python slicing comprehension