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.
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 #[M]onty Python print(first_letter) last_letter = phrase[-1] #Monty Pytho[n] print(last_letter) fifth_letter = phrase #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.
Nat Dunn founded Webucator in 2003 to combine his passion for web development with his business expertise and to help companies benefit from both.