In Python, we define a string, as shown below.
Define a string in Python and assign it to a variable.
We can access a single character by subscript, as with all languages, subscript starting from 0 (= = I think I write a good brain.)
At this point, we can use slicing to intercept a part of our defined string.
There are two ways to use slices: 1. Simple slices without step size
The syntax format is this:
1. First define a grid string, such as Hebe, and assign it a value
2. To intercept a part of a string, the syntax we use is Hebe [Start:stop]
Note: Here, the start is a string to intercept the beginning of the subscript, stop is the end of the string ending the previous position, this position you can understand to put the backslash, then the display of characters is the first stop subscript ... The first one, the last one (the important thing we say a few more times.) )
From the above diagram, we can see that if you intercept a specific position from the beginning, you can use [: a] to represent
[python] view plain copy >>> Hebe = "Xiaoxingyun" >>> hebe[:3] ' xia '
If you intercept from one beginning to the last one can be represented by [a:]
[python] view plain copy hebe[4:] ' Xingyun '
Here's a point to note that the index number of a string in Pyhton can be positive or negative, starting with-1:
[python] view plain copy >>> Hebe = "Xiaoxingyun" >>> hebe[-1] ' n ' >>> hebe[-2 ] ' u ' >>> hebe[-3] ' y ' >>> hebe[-4] ' g '
So we can also play this way:
[python] view plain copy >>> hebe[-3:] ' Yun '
2. Slice method with step size
Another way to slice is to first define a variable for a single string, and then remove the characters from our string at intervals.
Syntax format:
s [Start:stop:stride]
Similarly, the end character of the string being fetched here is the previous character of the Stop end
Stride represents the interval of the fetch string
Let's look at a few examples:
At this point, we can also retrieve a string in reverse.
[python] view plain copy >>> hebe= "Xiaoxingyun" >>> Length=len (Hebe) >>> hebe[:: -1] ' Nuygnixoaix ' >>>
The interval is reversed to remove a grid string:
[python] view plain copy >>> hebe[::-2] ' Nynxax '
The string of the intercept part of the direction:
This time we set the step size to a negative number, representing a right-to-left string, and the absolute value of the step is greater than 1 to denote the interval
The first part of the intercept subscript is also calculated from a negative number, or start must be greater than the end of the subscript, because it is a start from the right to intercept
That's the way Python strings are.