简体   繁体   中英

string from readline start from 1 in python?

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

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.

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 (ie the for loop is not executed). If you need to count backwards, then use an inclusive end bound and exclusive begin bound.

因为切片从字符0之前到字符2之前。即从字符0之前到字符1之后。即,前两个字符以字符0开头。

在Python切片中,指定所需的第一个项目,然后指定您想要的第一个项目。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM