1. SlicingThe sequence in Python includes string, list, tuple, sequence can use slice operation, can take the slice operation to obtain the corresponding type of variable of any part (subset)For example s= "HelloWorld", we can get "Hello" by slicing Operation S[0:5]. The subscript for the sequence is starting at 0.from left to right, subscript range: [0,len (s)-1)right-to-left, subscript range: [-len (s), -1]
2. sectioning ExampleThe syntax for a slice is: [Start:end:step]indicates starting from subscript start, step across with step, the following Mark End-1 end (not including end)
give an example of why the end of the slice does not include the subscript end
Case:in text processing, we often find a special symbol in the text, such as in the HTML text, to extract <a href= "www.test.com" > URL </a> inside the hyperlink www.test.com. Next we need to locate the href= "and" >, assuming Startpos and Endpos, respectively.so hyperlink content S=srchtml[startpos+6:endpos], at this time can be conveniently used endpos, without the hassle of minus 1
The following is an example of s= "Hello" Scenario 1: s[1:], The result is Ello, which indicates that the character starting with the subscript 1 starts fetching until the end of the string Scenario 2: S[:3], result Hel, indicates starting from string until subscript is 3-1=2 (not including subscript 3) Case 3: S[1:3], The result El, is taken from subscript 1, until the subscript is 3-1=2. Scenario 4: s[-5:-1], result hell, indicates starting from the first character, until the second last character (including), negative subscript operation Scenario 5:s[:], s[::], result Hello, means omit start subscript, stop subscript, step value to indicate take all Case 6: s[::-1], The result Olleh, means omitting the starting subscript, terminating subscript, the step value is-1, that is, reverse fetch
3. Multidimensional slicingThe principle is the same as one-dimensional slicing, except that there is an increase in dimensions Example: s[1:10, 3:20] # multidimensional slices
Python slicing operations