One character at a time
A string is a row of characters, and each character has a number that tells its place: its index. Indexes start from 0, not 1. The first character has the index 0, the second has 1, and so on:
p y t h o n
0 1 2 3 4 5
To get a single character, write its index in square brackets after the string:
word = "python"
print(word[0])
print(word[1])
print(word[5])
p
y
nThe result is a string too, one character long, so you can join it, compare it and print it like any other string.
The last character
A string of 6 characters has the indexes 0 to 5: the last index is always one less than the length. So for a string of any length, the last character is at len(text) - 1.
In a word chain game, each word must start with the letter the previous word ended with. This program checks one link of the chain, comparing the first character of the new word with the last character of the old one:
old = input("Previous word: ")
new = input("Your word: ")
if new[0] == old[len(old) - 1]:
print("Good link!")
else:
print("Your word should start with " + old[len(old) - 1])
python
applePrevious word: python
Your word: apple
Your word should start with nIndexError
Asking for an index that the string doesn't have stops the program. A very common slip is to use the length itself as the last index:
word = "cat"
print(word[len(word)])
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(word[len(word)])
~~~~^^^^^^^^^^^
IndexError: string index out of range"cat" has the indexes 0, 1 and 2, and len(word) is 3. "Out of range" means the index is outside the indexes the string has.
Every character in turn
With a helper variable as the index, a loop can visit the characters one by one. It goes on while the index is below the length, so the last round has the index len(word) - 1:
word = "loop"
index = 0
while index < len(word):
print(f"{index}: {word[index]}")
index += 1
0: l
1: o
2: o
3: p