String Indexing
In Python, we can access a certain/individual item in a sequence if the data type is indexable.
To index/access a single item from a string, we use [ ] square brackets.
NOTE:
Indexing always starts at 0 (zero)
Indexing always accesses a single item from the sequence, for strings: a character from the targetted string
The index value cannot go beyond the limit of the sequence. Mathematically, the index value cannot be greater than length of the sequence subtracted by one.
Examine the error for
print('word[6]:', word[6])
: gives us index out of range error
Notice that our index value in this diagram starts at the left of the item
When we index, it will go to the given location and look at the item to the right of the index
Therefore,
print('word[1]:', word[1])
gives us:e
Negative Indexing
Just like how we can use positive integer-indexes to access values, we can also use negative integer-indexes to access values as well.
NOTE:
Index of
-1
is the quickest way to grab the last value of an indexable sequenceExamine that at -6 and 0 we got the value of
H
forHello!
, they are located at the same place
Much like how we look at the right of positive indexes, we do the same for negative indexes
The indexes are laid out like an integer line with the string itself duplicated; however, Python does not actually create the string as a double
It is smart enough to know how to handle positive and negative indexes with a single instance of the sequence
Last updated