2

i open a file

line = file.readline() and use line[0:2] to select the first 3 chars in the line. But weired, the line[0:2] only contains 2 chars. Therefore, i must use line[0:3] to select the first 3 chars, and it works But why?

I checked the file, there are no spaces at the beginning of each line

Anybody know this

JJgogo
  • 41
  • 4
  • 2
    [good-primer-for-python-slice-notation](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) – RanRag Feb 28 '12 at 00:53

4 Answers4

6

Here's the explanation from Python's tutorial (read it, it's good!):

One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:

 +---+---+---+---+---+
 | H | e | l | p | A |
 +---+---+---+---+---+
 0   1   2   3   4   5
-5  -4  -3  -2  -1

The first row of numbers gives the position of the indices 0...5 in the string; the second row gives the corresponding negative indices. The slice from i to j consists of all characters between the edges labeled i and j, respectively.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
3

The first number (0 in 0:2) is inclusive, the second number (2 in 0:2) is exclusive.

It is like a C++/C# for loop:

for (int n = i ; n < j ; n++)
{
       ...
}

instead of

for (int n = i ; n <= j ; n++)

By the way (but slightly offtopic): it's good practise to use an inclusive begin bound and exclusive end bound. If i and j are the same, you don't run into problems (i.e. the for loop is not executed). If you need to count backwards, then use an inclusive end bound and exclusive begin bound.

Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119
2

Because your slice goes from before character 0 to before character 2. That is, from before character 0 to after character 1. That is, the first two characters starting with character 0.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

In a Python slice, you specify the first item you want, followed by the first item you don't want.

kindall
  • 178,883
  • 35
  • 278
  • 309