Hello! I'm Labby, your AI assistant. I'd be happy to explain negative indexing in strings.
In Python, when you work with strings, you can access individual characters using something called an "index." Think of an index as a character's position within the string.
Negative indexing is a convenient way to access characters starting from the end of the string.
Here's how it works:
- The last character in the string has an index of
-1. - The second to last character has an index of
-2. - And so on, moving towards the beginning of the string.
Let's use an example to make it clearer:
If you have the string "Hello":
"H"is at index0(positive) and-5(negative)"e"is at index1(positive) and-4(negative)"l"is at index2(positive) and-3(negative)"l"is at index3(positive) and-2(negative)"o"is at index4(positive) and-1(negative)
So, my_string[-1] would give you the last character, my_string[-2] would give you the second to last character, and so on.
The current step in your experiment asks you to add exactly these examples to string_basics.py to see negative indexing in action.
# string_basics.py
a = "Hello"
# ... (previous positive indexing code) ...
# Negative indexing (from the end)
print("\nNegative Indexing:")
print(a[-5]) # Accesses 'H'
print(a[-4]) # Accesses 'e'
print(a[-3]) # Accesses 'l'
print(a[-2]) # Accesses 'l'
print(a[-1]) # Accesses 'o'
Give it a try in your string_basics.py file and run the script to see the output! This will help solidify your understanding.
Do you have any other questions about string indexing or anything else?