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
0in the[]so that variablecommais set to the value, - Must use negative index
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules