Editor settings

General settings

Save settings

Learn to program with Python

Access a letter in a string with a negative index #

In the previous lesson, we learn that an index is a numeric value that represents the position of an element within a sequence, such as a string or a list. The first element in a sequence has an index of 0, the second has an index of 1, and so on.

In Python, negative index refers to indexing in reverse order, starting from the end of the sequence. The last item has an index of -1, the second last item has an index of -2, and so on.

For example:

my_string = "Hello, World!"
last_character = my_string[-1]
print(first_character) # Output: !

Exercise #

  • Change the number 0 in the [] so that variable comma is set to the value ,
  • Must use negative index
Output will be displayed here