Slicing is a common practice for strings in Python, which we'll cover in detail in this article, which is to get sub-characters or substrings.
In fact, all we have to do is use the index, separated by a colon, two indexes in the form of: variable [header subscript: tail subscript], the number before the colon indicates where the start is, and the number after the colon indicates the end position. This is a left-right open interval, which means that the string contains the header subscript, but does not contain a trailing subscript.
Python's data is indexed in two ways: The leftmost one starts with 0, increments in turn, and the rightmost element index is-1, which decreases to the left.
The Python index is flexible enough to select the appropriate index for the specific situation.
String index
Use an index to get a character in a string, use the subscript [x] directly, and don't forget that the index starts at 0 Oh!
For example a string language= "Python", using language[1] and using lanuage[-5] can get ' P '.
Split Slice interception
Python's slicing operations, often using a split slice, are used to split the string using a colon (:) in [].
Take say_hell= ' Hello ' for example:
As mentioned above, the usage syntax for slices is: string variable name [X:y], which represents a string of subscripts from X to Y (excluding y). When x is not written as, like [: y], it means starting from scratch, which is equivalent to [0:y]. When y does not write, it is always to the end. When both X and y two are not written, the entire string is represented.
Step Slice interception
Step interception, different from the previous slice interception operation, it is based on a certain number of "steps" to take the value.
The use syntax is:
Use a two colon, such as
Python code
[X::y]
, x means starting with x, y means taking the Y step to take a value, then to the end of the fetch. For example, before the STR [1::3], that is, starting from the second character, every 3 displacement to take a value, the result is EO.
try!
We've learned to work with and slice strings, so now it's time to consolidate and do a little exercise:
Strings can be concatenated using (+), or they can be duplicated using (*).
The string can be accessed using the index (Str[index]).
The string supports slicing, and in [] uses a colon: to split a string to intercept a string.
Strings can be intercepted using step [x::y] slices.
Using the previously learned knowledge, intercept "I am learning the HTML from mayacoder!", output "I am learning the Python from mayacoder!", do not forget the space is also the character Oh.
Think about it Oh ~ ~
The code answer is this (not the only one):