[issue43076] str.split() indexing issue

Steven D'Aprano report at bugs.python.org
Sat Jan 30 03:29:30 EST 2021


Steven D'Aprano <steve+python at pearwood.info> added the comment:

Hi Aleksandr,

In future, when posting what you think might be a bug, please try to cut the code down to the bare minimum needed. In this case, it doesn't matter at all that the strings you are processing come from splitting a larger string. split() has done its job, correctly, giving you a list of  substrings

    ['WORD', 'BIRD\nBIRD\nBIRD']

You then extract each item, and only then take the slice from it. So you can simplify the problem:

    string = 'WORD'
    print(string[0:3])

You ask:

"Shouldn't index [0:3] give 4 chars?"

No. It gives *three* characters. The end index is not included in the slice. Slice indexes occur *between* the characters:

    |W|O|R|D|
    0.1.2.3.4

so a slice from 0 to 3 includes only three characters, not four.

----------
nosy: +steven.daprano
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue43076>
_______________________________________


More information about the Python-bugs-list mailing list