One: Takes the first character of a string
print "Hello" [0] indicates the first character in the output string
print "Hello" [-1] indicates the last character in the output string
Two: String segmentation
print "Hello" [1:3]
#第一个参数表示原来字符串中的下表
#第二个阐述表示分割后剩下的字符串的第一个字符 subscript in the original string
This sentence is a bit verbose, directly look at the output:
El
Three: Several special cases
(1) print "Hello" [: 3] Start with the first character intercept
(2) print "Hello" [0:] intercept from the first character and intercept to the last
(3) print "Hello" [:] the same (2)
Look at the results of the output:
Hel
Hello
Hello
Four: Step intercept
print "Hello" [:: 2]
print "Hello" [::-2]
Represents the intercept from the first character and takes one of the 2 characters in each interval.
Output Result:
Hlo
Olh
Python-to-string slicing
Slicing the string
The string ' xxx ' and the unicode string U ' xxx ' can also be viewed as a list, each element being a character. Therefore, a string can also be manipulated with a slice, but the result of the operation is still a string:
>>> ' ABCDEFG ' [: 3]
' ABC '
>>> ' ABCDEFG ' [-3:]
' EFG '
>>> ' ABCDEFG ' [:: 2]
' Aceg '
In many programming languages, there are many kinds of interception functions available for strings, in fact, the purpose is to slice the strings. Python does not have an intercept function for a string, it can be done simply by slicing one operation.