Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python character slice interpretation


May 30, 2021 Article blog



Today when small editor in the study of Python, learn the slice character part, there are always many doubts, why clearly , but the output is always output to 4, not to 5. Let's give an example:

test1 = 'Hello World!'

test2 = "w3cschool!"

print ("test1[0]: ", test1[0])

print ("test2[1:5]: ", test2[1:5])

Results:

test1[0]: H

test2[1:5]: 3csc

parse:

In the code above, the first print is well understood, because the index of the code usually starts at 0, and for test1 , 'Hello World!', the index number is

character H e l l o W o r l d !
The index number 0 1 2 3 4 5 6 7 8 9 10 11

As can be seen from the index number above, print ("test1": ", test1") should output characters with an index of 0, i.e.: H.

character w 3 c s c h o o l !
The index number 0 1 2 3 4 5 6 7 8 9

At this time, the small compilation of the same reason to think of the second print - print ("test2 1:5": ", test2 ,1:5)) through the table above can be found, should be output: 3csch. R esults printed out of the result is: 3csc small editor is Best not sister, why, and then learn, the heart has been remembering this problem, almost all hair (hastened to touch the head there is no another bald point!!!

After looking for information, it was found that in Python, if the interception is used, then this interception takes the principle of left closed right open, the right side of the interception is the open ring, that is, does not contain, as written above test2, 1:5, where 5 is not included, so the final output, in fact, only printed to 4 is over. The output should therefore be 3csc.

summary

  1. In python, you can use the . . . to intercept characters
  2. If the intercept in Python uses the principle of left closed right open, left side contains, and right-hand element is not included.
  3. The intercepts of strings, lists, and tuples in Python apply to the above principles