Unlike other languages, Python does not throw an error when we try to access string characters with negative indices. They were introduced as an easier way to access characters from the end of a string without using the len() function.
For example, we can use the index -1 to select the last character of a string, even when we don’t know the string's length:
plant = "ficus"
print(plant[-1]) # Output: s
In general, writing string[-x] is equalivalent to writing string[len(string) - x]. We can access every character of a string using negative indices:
car = "ford"
print(plant[-1]) # Output: d
print(plant[-2]) # Output: r
print(plant[-3]) # Output: o
print(plant[-4]) # Output: f
Slicing characters from the end:
Negative indices are also useful for slicing some characters from the end of a string:
message = "Hello world"
# Slicing last 4 characters:
lastChars = message[-4:]
print(lastChars) # Output: orld
# Slicing last 7 characters:
lastChars = message[-7:]
print(lastChars) # Output: o world
In general, if you want to slice the last n characters, you use message[-n:].
Assignment
Follow the Coding Tutorial and let's practice with negative indices!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
