How to Index Strings in Python
Indexing is the process of finding a specific element within a sequence of elements through the element's position. Remember that strings are basically sequences of characters. We can use indexing to find a specific character within the string.
- If we consider the string from left to right, the first character (the left-most) is at position
0
. - If we consider the string from right to left, the first character (the right-most) is at position
-1
.
The table below illustrates this for the phrase "MONTY PYTHON".
The following code shows how to find characters by position using indexing.
phrase = "Monty Python"
first_letter = phrase[0]
#[M]onty Python
print(first_letter)
last_letter = phrase[-1]
#Monty Pytho[n]
print(last_letter)
fifth_letter = phrase[4]
#Mont[y] Python
print(fifth_letter)
third_letter_from_end = phrase[-3]
#Monty Pyt[h]on
print(third_letter_from_end)
The expected output for each call to print()
is shown in square brackets in the preceding comment.