Every character has a position
Each character in a string has a number called its index. Counting starts at 0, not 1.
For the word PYTHON:
| Character | P | Y | T | H | O | N |
|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative index | -6 | -5 | -4 | -3 | -2 | -1 |
word = "PYTHON"
print(word[0])
print(word[3])
print(word[-1])Output
P H N
Negative indexes count from the end. word[-1] is always the last character – very handy!
Common mistake:
word[6]gives anIndexErrorbecause the last index of a 6-letter word is 5.
Slicing: cutting out a piece
text[start:stop] gives the characters from start up to, but not including, stop.
Think of it like this: Slicing is like cutting a loaf of bread.
[1:4]means: start cutting at slice 1, stop just before slice 4.
word = "PYTHON"
print(word[0:2])
print(word[2:5])Output
PY THO
Leave out the start to begin at the start, or leave out the stop to go to the end:
word = "PYTHON"
print(word[:3])
print(word[3:])
print(word[-3:])Output
PYT HON HON
Reversing a string
A third number is the step. A step of -1 walks backwards, which reverses the string:
word = "PYTHON"
print(word[::-1])
print(word[::2])Output
NOHTYP PTO
Remember: Strings can't be changed in place.
word[0] = "J"gives an error. Instead, build a new string:"J" + word[1:].