Counting from the end
word[len(word) - 1] gets the last character, but Python has a shorter way: negative indexes, which count from the end. The index -1 is the last character, -2 the one before it, and so on:
p y t h o n
-6 -5 -4 -3 -2 -1
word = "python"
print(word[-1])
print(word[-2])
print(word[-6])
n
o
pword[-1] is always the same character as word[len(word) - 1], whatever the length of the word. Negative indexes run out too: "python" has nothing at the index -7, so word[-7] is an IndexError, just as word[6] is.
Empty input
When the user just presses Enter, input gives the empty string. It has no characters, so it has no first or last character, and every index is out of range:
This program makes an English noun plural in a simple way: a word that ends in s, such as bus, gets es, and any other word gets s. Pressing Enter without a word stops it:
word = input("Word: ")
if word[-1] == "s":
print(word + "es")
else:
print(word + "s")
Traceback (most recent call last):
File "main.py", line 2, in <module>
if word[-1] == "s":
~~~~^^^^
IndexError: string index out of rangeWhen a program can get an empty string, check the length before you use an index. Here the check comes first, so by the time Python gets to word[-1], the word has at least one character:
word = input("Word: ")
if len(word) == 0:
print("No word, no plural")
elif word[-1] == "s":
print(word + "es")
else:
print(word + "s")
Word:
No word, no pluralBackwards through a string
A loop can go through a string from its end. Here the index starts at -1 and goes down by one in every round, until it has passed the first character, which is at -len(word):
word = "stressed"
backwards = ""
index = -1
while index >= -len(word):
backwards += word[index]
index -= 1
print(backwards)
dessertsstressed has 8 characters, so -len(word) is -8. The loop runs with the indexes -1, -2 and so on down to -8, adding one character in every round, and ends when index is -9. The same works with ordinary indexes: start from len(word) - 1, the last index, and go down while the index is at least 0.