As we mentioned earlier, strings are treated as an ordered collection of characters. To access these characters individually, you need to reference the string they are in and their location within the string, called the index.
For example, if you wanted to print the :
word = "Hello"
print(word[1])
Python, and most popular programming languages, use 0-based indexing, which means instead of the first character having an index of 1, it has an index of 0.
You can see below the indexing of the string "Hello". The code above would actually print "e" instead of "H".
You can find the length of a string or list using the len() command. len("Hello") would return 5.
Notice that the index of the last character is one less than the length. If you want the last character of a string, you can use string[len(string) - 1].
However, Python supports negative indexing, which assigns a negative index on top of the "normal" index. This is useful when trying to get characters from the end of the string.
Python assigns the index -1 to the last character and decreases by one as you move to the left of the string. (This is shown in the example above.)
Positive Indexing
0
1
2
3
...
len(string ) -3
len(string) - 2
len(string) - 1
Using Positive and Negative
0
1
2
3
...
-3
- 2
- 1