Python Forum
Need guidance on String indexing - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Need guidance on String indexing (/thread-19304.html)



Need guidance on String indexing - Gateux - Jun-22-2019

Am learning Python for school and reading a Python textbook, I come across one part that I don't understand.

>>> grades = ['A', 'B', 'C', 'D', 'F']
>>> grades[2:4]
['C', 'D']
Going by the Python String Indexing logic, the first position starts from 0 so by logic, 'A' is 0 and the output 'C' is correct which is 2. But I don't understand why 4 is 'D' when it should been 'F' instead since Indexing starts from 0.

Is there a mistake in the book? or am I missing something here? Please advise, thanks.


RE: Need guidance on String indexing - Yoriz - Jun-22-2019

When slicing the start is always included, and the end always excluded.


RE: Need guidance on String indexing - ichabod801 - Jun-22-2019

I like to think of slicing as the indexes being between numbers:

Output:
['A', 'B', 'C', 'D', 'E'] ^ ^ ^ ^ ^ ^ | | | | | | 0 1 2 3 4 5
If you just index (grades[3]) you get the item after the index ('D'). And if you get a full slice (grades[2:4]), you get everything between the numbers (['C', 'D']).

Of course, understanding it the way Yoriz explained it is good to, because that's the way range() works.


RE: Need guidance on String indexing - perfringo - Jun-22-2019

Add-on way to think: how many characters should slice [2:4] return? 4 - 2 = 2 (it’s always stop- start = number of elements). If first is included then last should be excluded in order to get right number of characters.