This article mainly introduces the information about the string slicing operation in Python. For more information, see
I. number of characters in the string
Print "Hello" [0] indicates the first character in the output string
Print "Hello" [-1] indicates the last character in the output string
Ii. string segmentation
Print "Hello" [1: 3]
# The first parameter indicates the following table in the original string
# The second description indicates the subscript of the first character of the remaining string after segmentation in the original string
This sentence is a bit wordy. Let's look at the output result directly:
El
Iii. Special situations
(1) print "Hello" [: 3] starting from the first character
(2) print "Hello" [0:] is truncated starting from the first character until the last character.
(3) print "Hello" [:] Same principle (2)
View output results:
El
Hello
Hello
4. Step Size Truncation
Print "Hello" [: 2]
Print "Hello" [:-2]
It indicates that the string is truncated from the first character, and the interval is 2 characters.
Output result:
Hlo
OlH
Python slice strings
Slice string
The string 'xxx' and the Unicode string u'xxx' can also be considered as a list. Each element is a character. Therefore, the string can also be sliced, but the operation result is still a string:
>>> 'Abcdef' [: 3]
'Abc'
>>> 'Abcdef' [-3:]
'Efg'
>>> 'Abcdef' [: 2]
'Aceg'
In many programming languages, many types of truncation functions are provided for strings. The purpose is to slice strings. Python does not have a function to intercept strings. You only need to slice an operation to complete the process, which is very simple.