
Code
Letter by Letter
A string is a row of characters, and every character has a numbered position called an index. Python starts counting at 0, not 1:
L A N T E R N
0 1 2 3 4 5 6
-7 -6 -5 -4 -3 -2 -1
Put the index in square brackets to grab one character:
word = "LANTERN"
print(word[0]) # L (the first)
print(word[3]) # T
print(word[-1]) # N (negative counts from the end)
print(len(word)) # 7 (how many characters)
Negative indexes are a shortcut: -1 is always the last
character, -2 the one before it, and so on.
Pip tip: The last index is
len(word) - 1. Asking forword[7]here causes an IndexError. There's no 8th letter!
Assignment
Using scroll (don't type the letters yourself):
- Set
firstto the first character. - Set
lastto the last character, using a negative index. - Set
thirdto the third character. - Set
sizeto the number of characters, usinglen().
Using scroll (don't type the letters yourself):
- Set
firstto the first character. - Set
lastto the last character, using a negative index. - Set
thirdto the third character. - Set
sizeto the number of characters, usinglen().
main.py Python sleeping
Press Run to try your code, then Check to test it.