Quick check
For city = "Lisbon", what are city[0], city[3] and city[len(city) - 1]?
Show the answer
Answer: "L", "b" and "n". The indexes of Lisbon run from 0 to 5.
Ultimate Core Python · Chapter 8
This lesson goes with Episode 8 of the Ultimate Core Python course on the Core by Critic channel on YouTube.
A string is a sequence, so each character has a place in the order. That place is called its index (the plural is indexes or indices). Here is the string "Python" with the index of each character written underneath:
┌───┬───┬───┬───┬───┬───┐
│ P │ y │ t │ h │ o │ n │
└───┴───┴───┴───┴───┴───┘
0 1 2 3 4 5
To read one character, write the index in square brackets after the string:
word = "Python"
print(word[0])
print(word[1])
print(word[5])Output
P y n
word[0] is read aloud as "word at zero" or "word sub zero". What you get back is itself a string, one character long. Python has no separate "character" type:
word = "Python"
print(type(word[0]))
print(len(word[0]))Output
<class 'str'> 1
It feels strange at first. The best way to think about it: the index is not "which character", it is how far from the start. The first character is zero steps from the start. The second is one step away. A ruler works the same way: the first centimetre begins at the mark labelled 0.
Two facts follow from this, and they are worth memorising:
0.len(word) - 1. For a 6-character string, that is 5. There is no index 6.word = "Python"
print(len(word))
print(word[len(word) - 1])Output
6 n
Anything that works out to a whole number can go inside the brackets:
word = "Python"
position = 2
print(word[position])
print(word[position + 1])
print(word[len(word) // 2])Output
t h h
The last line picks the character at the middle position: 6 // 2 is 3. Indexing also works directly on a literal, and on anything that gives a string:
print("Tokyo"[0])
print(str(2026)[3])Output
T 6
str(2026) is "2026", and its character at index 3 is "6". That is how you pick a digit out of a number: convert it to text first.
Quick check
For city = "Lisbon", what are city[0], city[3] and city[len(city) - 1]?
Answer: "L", "b" and "n". The indexes of Lisbon run from 0 to 5.
Predict the output
What does it print?
word = "planet"
print(word[0])
print(word[3])
print(word[len(word) - 1])Counting starts at zero, so index 3 is the fourth character.
len(word) is 6, so the last line asks for the character at index 5.
It prints
p n t
An index says how far a character is from the start. The first character is at index 0 and the last one is at len(word) - 1.
Fill in the blank
Fill in the blank so that the program prints the first character of the word.
word = "Tokyo"
print(word[])The finished program prints:
Target
T
The index is the distance from the start of the string.
The first character is zero steps from the start.
word = "Tokyo"
print(word[0])Counting starts at zero, so the first character of every string is at index 0.
Fix the bug
This should print the last digit of the whole number that the user types. It crashes. Fix it.
With the reply 4096, the program prints the lines below. Your program must print exactly these lines.
Example run
6
Output
Square brackets work on a string. What type is number after int()?
To pick a digit out of a number, the number must be text. The reply from input() is text already.
number = input("Whole number: ")
print(number[-1])An int has no positions, so it cannot be indexed. Keep the reply as text, or turn the number into text with str(), and then index it.
Often you want the last character, or the one before it. Writing word[len(word) - 1] every time is clumsy, so Python lets you count from the end with negative indexes. -1 is the last character, -2 the one before, and so on:
┌───┬───┬───┬───┬───┬───┐
│ P │ y │ t │ h │ o │ n │
└───┴───┴───┴───┴───┴───┘
0 1 2 3 4 5 counting from the front
-6 -5 -4 -3 -2 -1 counting from the back
word = "Python"
print(word[-1])
print(word[-2])
print(word[-6])Output
n o P
Every character therefore has two addresses. The rule connecting them: word[-k] is the same character as word[len(word) - k]. Python simply adds the length to a negative index for you.
Why does the back start at -1 and not -0? Because -0 is just 0, which already means the first character.
Predict the output
What does it print?
word = "garden"
print(word[-1])
print(word[-3])
print(word[-len(word)])-1 is the last character, -2 is the one before it, and so on.
-len(word) is -6 here. For a word with six characters, that is as far back as you can go.
It prints
n d g
Negative indexes count from the end. word[-1] is the last character and word[-len(word)] is the first one.
Multiple choice
For word = "silver", which of these is the same character as word[-2]?
Python adds the length of the string to a negative index.
The word has 6 characters. Work out 6 minus 2.
The answer is: word[4]
word[-k] is the same character as word[len(word) - k]. Every character has two indexes: one from the front and one from the back.
IndexErrorAsk for a position that does not exist and Python stops with an IndexError:
word = "Python"
print(word[6])Output
Traceback (most recent call last):
File "index.py", line 2, in <module>
print(word[6])
~~~~^^^
IndexError: string index out of rangeOut of range means the index is outside the set of legal positions. For a string of length n:
| Legal indexes | For "Python" (length 6) |
|---|---|
from 0 to n - 1 |
0, 1, 2, 3, 4, 5 |
from -n to -1 |
-6, -5, -4, -3, -2, -1 |
Anything else, such as 6, 10 or -7, is an error.
The empty string has no legal index at all. Even ""[0] is an IndexError, because there is no first character. This matters when the string comes from the user: if they press Enter without typing anything, reply[0] crashes.
A position cannot be a decimal or a piece of text:
word = "Python"
print(word[1.0])Output
Traceback (most recent call last):
File "index.py", line 2, in <module>
print(word[1.0])
~~~~^^^^^
TypeError: string indices must be integers, not 'float'Even 1.0, which is a whole value, is refused because its type is float. This bites when the index comes from a division: len(word) / 2 is always a float (Chapter 4). Use // to get an int. It also bites when the index comes from input(), which gives text: convert it with int() first.
Quick check
Which of these are errors for s = "code"? s[4], s[-4], s[-5], s[2 / 2]
Answer: s[4] and s[-5] are IndexError (legal indexes are 0 to 3 and −4 to −1). s[2 / 2] is a TypeError, because 2 / 2 is the float 1.0. Only s[-4] works, and gives "c".
Multiple choice
What happens when this program runs?
word = "river"
print(word[5])Count the characters of river. Which indexes are legal?
For a string of length 5, the legal indexes from the front are 0 to 4.
The answer is: It stops with an IndexError
The last index is one less than the length. Index 5 does not exist in a string with 5 characters, so Python stops with an IndexError.
Fix the bug
The user types a position counted the everyday way: 1 means the first letter and 6 means the last letter. The program should print that letter. Now it prints the wrong letter, and for 6 it crashes. Fix it.
With the reply 1, the program prints the lines below. Your program must print exactly these lines.
Example run
b
Output
Python counts from 0, but the user counts from 1.
The index is always one less than the everyday position.
word = "bridge"
position = int(input("Position (1 to 6): "))
print(word[position - 1])This is the off-by-one mistake. The first letter is at index 0, so the everyday position must be reduced by 1.
Indexing gives one character. Slicing gives a whole section. Write two indexes separated by a colon:
word = "Python"
print(word[0:2])
print(word[2:6])
print(word[1:4])Output
Py thon yth
The form is word[start:stop], and the rule is:
The slice begins at
startand goes up to, but does not include,stop.
So word[1:4] is the characters at indexes 1, 2 and 3. Index 4 is where it stops, and that character is left out.
"Up to but not including" is easier to get right with a different picture. Stop thinking of indexes as pointing at the characters. Think of them as pointing at the gaps between the characters, like the posts of a fence, with the characters as the panels between the posts:
┌───┬───┬───┬───┬───┬───┐ │ P │ y │ t │ h │ o │ n │ └───┴───┴───┴───┴───┴───┘ 0 1 2 3 4 5 6
A slice is a cut at two posts. word[1:4] cuts at post 1 and post 4 and gives you everything in between: y, t, h. With this picture there is nothing to remember about including or excluding. You get what lies between the two cuts.
The picture also explains why 6 is allowed as a stop for "Python", although word[6] is an error: there is a post 6, at the very end, but there is no panel after it.
This design looks odd, but it gives three properties that make slices pleasant to work with:
word = "Python"
print(len(word[1:4])) # 1. the length is stop - start
print(word[0:2] + word[2:6]) # 2. pieces that share a boundary fit together
print(word[0:3]) # 3. [0:n] is "the first n characters"Output
3 Python Pyt
stop - start: 4 − 1 is 3.word[0:2] and word[2:6] share the number 2, and together they give the whole string with no overlap and no gap.word[0:n] is exactly the first n characters.If stop were included, all three would need a "plus one" or "minus one" somewhere, and that is where bugs live.
Quick check
For s = "notebook", what are s[0:4], s[4:8] and s[2:5]? How long is s[3:7]?
Answer: "note", "book" and "teb". s[3:7] has length 7 − 3, which is 4 (it is "eboo").
Predict the output
What does it print?
s = "sunflower"
print(s[0:3])
print(s[3:9])
print(len(s[2:7]))A slice begins at start and stops before stop.
The length of a slice is stop - start. You do not need to read the letters for the last line.
It prints
sun flower 5
stop is left out, so two slices that share a number fit together with no gap, and the length is stop - start.
Fill in the blank
Fill in the two numbers, both counted from the front, so that the program prints the last four letters of the word.
word = "football"
print(word[:])The finished program prints:
Target
ball
Use the fence-post picture: a word with 8 characters has posts 0 to 8.
The last four letters lie between the post in the middle and the post at the very end.
word = "football"
print(word[4:8])A slice is a cut at two posts. The post at the end has the same number as the length of the string, and it is a legal stop.
Both numbers in a slice are optional. Leave out start and the slice begins at the beginning. Leave out stop and it runs to the end:
word = "Python"
print(word[:2]) # from the beginning up to post 2
print(word[2:]) # from post 2 to the end
print(word[:]) # everythingOutput
Py thon Python
Read word[:2] as "the first two characters" and word[2:] as "everything except the first two". These two forms are what you will write most of the time.
For any string and any number n, the two halves always fit back together:
word = "Python"
n = 4
print(word[:n] + word[n:])
print(word[:n] + word[n:] == word)Output
Python True
You can think of word[:n] and word[n:] as cutting the string in two at post n.
Put the lines in order
Put the lines in order. The program asks for a text, drops its first two characters, keeps the first three characters of what is left, and prints them.
With the reply keyboard, the program in the right order prints:
Target
ybo
text = input("Text: ")short = rest[:3]print(short)rest = text[2:]A name must get its value before another line uses it.
short is made from rest, and rest is made from text.
text = input("Text: ")
rest = text[2:]
short = rest[:3]
print(short)text[2:] is everything except the first two characters, and rest[:3] is the first three characters of that piece.
Negative indexes work in slices exactly as they do in indexing: they count posts from the end.
┌───┬───┬───┬───┬───┬───┐ │ P │ y │ t │ h │ o │ n │ └───┴───┴───┴───┴───┴───┘ 0 1 2 3 4 5 6 -6 -5 -4 -3 -2 -1
word = "Python"
print(word[-3:]) # the last three characters
print(word[:-1]) # everything except the last character
print(word[1:-1]) # everything except the first and the last
print(word[-4:-2]) # between post -4 and post -2Output
hon Pytho ytho th
Two of these are worth learning by heart:
word[-n:] is the last n characters.word[:-n] is everything except the last n.They are the mirror images of word[:n] and word[n:].
Fill in the blank
Fill in the blank with a negative number and a colon, so that the program prints the last three characters of the file name.
name = "picture.png"
print(name[])The finished program prints:
Target
png
The form word[-n:] means the last n characters.
The slice starts three posts before the end, and the stop is left out.
name = "picture.png"
print(name[-3:])name[-3:] starts three characters before the end and runs to the end, for a name of any length.
Predict the output
What does it print?
s = "sandwich"
print(s[-4:])
print(s[:-4])
print(s[1:-1])s[-n:] is the last n characters. s[:-n] is everything except the last n.
s[1:-1] leaves out one character at each end.
It prints
wich sand andwic
Negative numbers in a slice count posts from the end. s[-4:] and s[:-4] are the two pieces of one cut.
Write code
Name and ending. Ask for a file name that ends with a dot and three letters, such as photo.png. Print two lines: first the file name without its last four characters, then only its last three characters.
With the reply photo.png, the program prints the lines below. Your program must print exactly these lines.
Example run
photo png
Output
The dot and the three letters are the last four characters.
name[:-n] is everything except the last n characters, and name[-n:] is the last n.
name = input("File name: ")
print(name[:-4])
print(name[-3:])Counting from the end works for a file name of any length, because the ending always has the same size.
Indexing is strict: a bad index is an IndexError. Slicing is forgiving. If a slice asks for more than exists, Python quietly gives whatever is there:
word = "Python"
print(word[2:100])
print(word[-100:3])
print(repr(word[10:20]))
print(repr(word[4:2]))Output
thon Pyt '' ''
word[2:100]: there is no post 100, so the slice stops at the end.word[-100:3]: there is no post −100, so the slice starts at the beginning.word[10:20]: both cuts are past the end, and nothing lies between them. The result is the empty string.word[4:2]: start is after stop, so again nothing is in between.Indexing s[i] |
Slicing s[i:j] |
|
|---|---|---|
| Gives back | one character | a string of any length, possibly empty |
| Out of range | IndexError |
no error; the slice is trimmed to fit |
| On an empty string | always an error | always "" |
This makes slicing the safe way to look at the start of a string that might be empty. reply[0] crashes on an empty reply; reply[:1] gives "".
reply = ""
print(repr(reply[:1]))Output
''
Multiple choice
For s = "tea", three of these give a string. Which one stops with an error?
Indexing is strict and slicing is forgiving.
Look for the one with no colon. Is that index legal for a string with 3 characters?
The answer is: s[3]
A slice is trimmed to fit and never raises an error. An index outside the legal positions is an IndexError.
Predict the output
What does it print?
s = "lamp"
print(len(s[2:50]))
print(repr(s[9:]))
print(s[-50:2])A number that is too large is trimmed to the end. A number that is too small is trimmed to the start.
When both cuts are past the end, nothing lies between them. repr() shows the quotes of the empty string.
It prints
2 '' la
Slices are trimmed to fit the string. When nothing is left, the result is the empty string, not an error.
Fix the bug
This program shows the first character of the reply. It crashes when the user presses Enter without typing anything. Fix it so that an empty reply gives an empty string.
With the reply , the program prints the lines below. Your program must print exactly these lines.
Example run
''
Output
The empty string has no legal index at all.
A slice never raises an error. Which slice means "the first one character"?
reply = input("Your reply: ")
print(repr(reply[:1]))reply[0] is an IndexError on an empty reply. reply[:1] gives the first character, or the empty string when there is none.
A slice can take a third number, the step: word[start:stop:step]. It says how far to jump each time. The default is 1, meaning every character.
digits = "0123456789"
print(digits[::2]) # every second character, from the start
print(digits[1::2]) # every second character, starting at index 1
print(digits[::3]) # every third character
print(digits[2:9:3]) # start at 2, stop before 9, jump 3Output
02468 13579 0369 258
For digits[2:9:3], Python takes index 2, then 5, then 8. The next would be 11, which is past the stop, so it ends there.
A negative step walks from right to left. The most famous slice in Python reverses a string:
word = "Python"
print(word[::-1])Output
nohtyP
With a negative step, the defaults flip: a missing start means the end of the string, and a missing stop means "go all the way past the beginning". So [::-1] starts at the last character and steps back one at a time until it runs out.
When you give explicit numbers with a negative step, start must be to the right of stop, and stop is still left out:
word = "Python"
print(word[4:1:-1]) # indexes 4, 3, 2
print(word[::-2]) # indexes 5, 3, 1
print(repr(word[1:4:-1])) # going left from 1 never reaches 4Output
oht nhy ''
A step of zero would never move, so it is not allowed: word[::0] raises ValueError: slice step cannot be zero.
Quick check
For s = "abcdefg", what are s[::3], s[::-1] and s[1:6:2]?
Answer: "adg" (indexes 0, 3, 6), "gfedcba", and "bdf" (indexes 1, 3, 5).
Predict the output
What does it print?
letters = "bcdfghjk"
print(letters[::2])
print(letters[1::3])
print(letters[::-1])The third number is the step. With a step of 2, Python takes indexes 0, 2, 4 and 6.
[1::3] starts at index 1 and jumps three places each time. A step of -1 walks backwards.
It prints
bdgj cgk kjhgfdcb
The step says how far to jump each time. A negative step walks from right to left.
Fill in the blank
Fill in the blank so that the program prints the word reversed.
word = "drawer"
print(word[])The finished program prints:
Target
reward
Leave out start and stop, and give only a step.
A step of -1 walks backwards, one character at a time.
word = "drawer"
print(word[::-1])[::-1] starts at the last character and steps back one at a time, which gives the reversed string.
Multiple choice
What happens when this program runs?
word = "stone"
print(word[::0])The step says how far to jump each time. How far does a step of zero jump?
A slice never raises an IndexError, but this step is a value that makes no sense.
The answer is: It stops with a ValueError
A step of zero would never move, so Python refuses it with ValueError: slice step cannot be zero.
Put the lines in order
Put the lines in order. The program asks for a word, cuts out the characters at indexes 1 to 3, reverses that piece, and prints it.
With the reply garden, the program in the right order prints:
Target
dra
piece = word[1:4]word = input("Word: ")flipped = piece[::-1]print(flipped)First cut the piece, then reverse it.
flipped is made from piece, so the line that makes piece comes first.
word = input("Word: ")
piece = word[1:4]
flipped = piece[::-1]
print(flipped)Two clear moves are easier to read than one slice with a negative step and explicit numbers: cut first, then reverse.
Chapter 7 said strings are immutable. Here is the proof. Square brackets can read a character, but they cannot write one:
word = "Python"
word[0] = "J"Output
Traceback (most recent call last):
File "change.py", line 2, in <module>
word[0] = "J"
~~~~^^^
TypeError: 'str' object does not support item assignmentItem assignment means "putting a new value at an index". Strings do not allow it, and they do not allow deleting a character with del word[0] either.
The way to "change" a string is always the same: build a new string from pieces of the old one. Slices give you the pieces and + joins them:
word = "Python"
new_word = "J" + word[1:]
print(new_word)
print(word)Output
Jython Python
word[1:] is everything except the first character. Put a J in front, and you have a new string. The original is untouched, as the second print shows. If you no longer need the old one, reuse the name: word = "J" + word[1:].
The same idea handles a change anywhere. To replace the character at position i, take everything before it, the new character, and everything after it:
word = "Python"
i = 3
print(word[:i] + "H" + word[i + 1:])Output
PytHon
word[:3] new word[4:] ┌───┬───┬───┐ ┌───┐ ┌───┬───┐ │ P │ y │ t │ │ H │ │ o │ n │ └───┴───┴───┘ └───┘ └───┴───┘
The same pattern inserts (use word[i:] for the second piece, so nothing is skipped) and deletes (leave out the middle piece):
word = "Python"
print(word[:2] + "---" + word[2:]) # insert at post 2
print(word[:2] + word[3:]) # delete the character at index 2Output
Py---thon Pyhon
It can feel like a restriction, but it is a deliberate gift. Because a string can never change, you can hand it to any part of a program and be certain it will come back the same. Two names can safely share one string. And strings can be used as keys for fast lookup in dictionaries → Chapter 31. When you do need a sequence of characters that you can edit in place, you use a list → Chapter 25.
Multiple choice
The error message for word[0] = "J" talks about item assignment. What does that mean?
Look at the line that fails. On which side of the = sign are the square brackets?
Reading with square brackets is allowed. The line tries to do the opposite.
The answer is: putting a new value at an index
Strings are immutable. Square brackets can read a character, but they cannot write one, so the assignment is a TypeError.
Fix the bug
This should print the word with the character at index 2 replaced by a dash. Now the old character is still there, and the result is one character too long. Fix it.
With the reply river, the program prints the lines below. Your program must print exactly these lines.
Example run
ri-er
Output
The first piece ends just before index i. Where does the last piece begin now?
To skip the old character, the last piece must start one post later.
word = input("Word: ")
i = 2
print(word[:i] + "-" + word[i + 1:])word[i:] still contains the old character, so that pattern inserts. To replace, the last piece is word[i + 1:].
Write code
Delete one character. Ask for a word first, then for a position (a whole number, counted from 0). Print one line: the word without the character at that position.
With the replies planet then 0, the program prints the lines below. Your program must print exactly these lines.
Example run
lanet
Output
Convert the position with int(). You cannot remove a character, so build a new string from two pieces.
The first piece is everything before the position. The other piece starts one post after it.
word = input("Word: ")
i = int(input("Position: "))
print(word[:i] + word[i + 1:])A string cannot be changed. To delete, join the piece before the position to the piece after it and leave the middle out.
These patterns come up constantly. Each one is just an index or a slice.
text = "programming"
print(text[0]) # first character
print(text[-1]) # last character
print(text[:3]) # first three
print(text[-3:]) # last three
print(text[1:]) # all but the first
print(text[:-1]) # all but the last
print(text[1:-1]) # without the first and the last
print(text[len(text) // 2]) # the middle character
print(text[::-1]) # reversed
print(text[::2]) # every other characterOutput
p g pro ing rogramming programmin rogrammin a gnimmargorp pormig
| You want | Write |
|---|---|
| First character | s[0] (or s[:1] if s might be empty) |
| Last character | s[-1] (or s[-1:] if s might be empty) |
First n characters |
s[:n] |
Last n characters |
s[-n:] |
Without the first n |
s[n:] |
Without the last n |
s[:-n] |
| Reversed | s[::-1] |
A copy with character i replaced |
s[:i] + new + s[i + 1:] |
Is it a palindrome? A palindrome reads the same in both directions, like level. Compare the string with its reverse:
word = "level"
print(word == word[::-1])
word = "lever"
print(word == word[::-1])Output
True False
Hide a card number. Show only the last four digits and replace the rest with stars:
card = "4929123456781234"
hidden = "*" * (len(card) - 4) + card[-4:]
print(hidden)Output
************1234
Rotate a string. Move the first n characters to the end, like passengers moving along a bench:
text = "abcdef"
n = 2
print(text[n:] + text[:n])Output
cdefab
Cut at post n, then join the two halves in the opposite order.
Fill in the blank
Fill in the blank so that only the last four characters of the code stay visible after the stars.
code = "731955204486"
hidden = "*" * (len(code) - 4) + code[]
print(hidden)The finished program prints:
Target
********4486
You need a slice, not one character.
The slice for "the last n characters" starts at -n and has no stop.
code = "731955204486"
hidden = "*" * (len(code) - 4) + code[-4:]
print(hidden)code[-4:] is the last four characters. The stars in front replace all the other characters, so the length stays the same.
Write code
Rotate to the left. Ask for a text first, then for a whole number n. Print one line: the text with its first n characters moved to the end.
With the replies bcdefg then 2, the program prints the lines below. Your program must print exactly these lines.
Example run
defgbc
Output
Cut the text in two at post n.
Join the two pieces in the opposite order: first everything after post n, then the first n characters.
text = input("Text: ")
n = int(input("How many: "))
print(text[n:] + text[:n])text[:n] and text[n:] cut the text at post n. Joining them the other way round moves the front piece to the end.
| The mistake | What you see | The fix |
|---|---|---|
Using s[1] for the first character |
The second character | The first is s[0] |
Using s[len(s)] for the last character |
IndexError: string index out of range |
s[-1] or s[len(s) - 1] |
Expecting s[2:5] to include index 5 |
One character fewer than expected | stop is left out; write s[2:6] |
An index from division: s[len(s) / 2] |
TypeError: string indices must be integers |
Use // |
An index from input() |
TypeError: string indices must be integers, not 'str' |
Convert with int() |
s[0] = "X" |
TypeError: 'str' object does not support item assignment |
s = "X" + s[1:] |
Round brackets: s(0) |
TypeError: 'str' object is not callable |
Indexing uses square brackets |
| Indexing a reply that may be empty | IndexError when the user just presses Enter |
Use a slice, reply[:1], or check first |
s[5:2] hoping for a reversed piece |
'' |
A backwards slice needs a negative step: s[5:2:-1] |
A comma instead of a colon: s[1,3] |
TypeError: string indices must be integers, not 'tuple' |
s[1:3] |
Put the lines in order
Put the lines in order. The program asks for a booking code such as TYO-20261123-0457-B, takes the year out of it, and prints the year that follows.
With the reply TYO-20261123-0457-B, the program in the right order prints:
Target
2027
year = int(code[4:8])next_year = year + 1code = input("Booking code: ")print(next_year)The slice needs the code, and the addition needs the year.
Follow the names: code first, then year, then next_year.
code = input("Booking code: ")
year = int(code[4:8])
next_year = year + 1
print(next_year)A slice gives text. int() turns the four digits into a number, and only then can the program add 1.
Questions with a Check button are checked on this page. Use the hints when you are stuck: the last step always shows the answer. The other questions show the book's answer, so that you can compare.
Check yourself
What is the index of the first character of a string? Of the last character of a string with 10 characters?
0. For 10 characters, the last index is 9.
Check yourself
Give two different ways to get the last character of name.
name[-1] and name[len(name) - 1].
Check yourself
Why is "Python"[6] an error although the string has 6 characters?
The six characters have indexes 0 to 5. Index 6 would be a seventh character, which does not exist.
Check yourself
What does s[2:5] give for s = "abcdefgh"? Which index is not included?
"cde": indexes 2, 3 and 4. Index 5 ("f") is not included.
Check yourself
In the fence-post picture, how many posts does a string of length 5 have?
Six: posts 0 to 5. There is always one more post than there are characters.
Check yourself
What do s[:4] and s[4:] have in common with the whole string s?
Joined together they give back s exactly: s[:4] + s[4:] == s.
Check yourself
What is the difference between s[10] and s[10:] when s has only 5 characters?
s[10] is an IndexError. s[10:] is the empty string, because slices are trimmed instead of raising.
Check yourself
What does the step in s[::3] do? What does s[::-1] do?
s[::3] takes every third character, starting at index 0. s[::-1] walks backwards one step at a time, giving the reversed string.
Check yourself
Why does s[0] = "X" fail? Write the correct way to get a new string with the first character replaced.
Strings are immutable, so a character cannot be assigned. Build a new string: s = "X" + s[1:].
Check yourself
Why must you write s[len(s) // 2] and not s[len(s) / 2]?
/ always gives a float, and an index must be an int. // gives an int.
Predict the output
s = "keyboard"
print(s[0], s[3], s[-1], s[-3])
print(s[len(s) - 2])Write the indexes 0 to 7 under the letters of keyboard. Negative indexes count from the end, starting at -1.
len(s) is 8, so the last line asks for the character at index 6.
It prints
k b d a r
len(s) - 2 is 6.
s = "keyboard"
print(s[0], s[3], s[-1], s[-3])
print(s[len(s) - 2])Output
k b d a r
Predict the output
s = "keyboard"
print(s[:3], s[3:], s[2:6])
print(s[-5:], s[:-5], s[-5:-2])s[:3] is the first three characters and s[3:] is everything after them.
s[-5:] is the last five characters, s[:-5] is everything except the last five, and stop is always left out.
It prints
key board yboa board key boa
s = "keyboard"
print(s[:3], s[3:], s[2:6])
print(s[-5:], s[:-5], s[-5:-2])Output
key board yboa board key boa
Predict the output
s = "0123456789"
print(s[::4], s[1::4], s[::-3])
print(s[8:2:-2], s[2:8][::-1])A step of 4 takes one character, then jumps four places. A negative step starts at the end and walks to the left.
For s[8:2:-2], start at index 8 and go down by 2, stopping before index 2. For the last one, cut s[2:8] first and reverse that piece.
It prints
048 159 9630 864 765432
s[8:2:-2] takes indexes 8, 6, 4. s[2:8] is "234567", which is then reversed.
s = "0123456789"
print(s[::4], s[1::4], s[::-3])
print(s[8:2:-2], s[2:8][::-1])Output
048 159 9630 864 765432
Predict the output
s = "data"
print(repr(s[4:]), repr(s[2:2]), repr(s[3:1]), repr(s[-99:1]))
print(len(s[1:100]))Slices never raise an error. A slice with nothing between its two posts is the empty string.
A number that is too large or too small is trimmed to the end or to the start of the string.
It prints
'' '' '' 'd' 3
s[-99:1] is trimmed to s[0:1].
s = "data"
print(repr(s[4:]), repr(s[2:2]), repr(s[3:1]), repr(s[-99:1]))
print(len(s[1:100]))Output
'' '' '' 'd' 3
Predict the output
s = "hello"
t = s[:1] + "a" + s[2:]
print(s, t)
print(t[::-1][0] + t[0])s[:1] is the first character and s[2:] starts at index 2, so the character at index 1 is the one that is replaced.
s itself never changes. On the last line, t[::-1][0] is the first character of the reversed string, which is the last character of t.
It prints
hello hallo oh
t is "hallo". t[::-1] is "ollah", whose first character is "o".
s = "hello"
t = s[:1] + "a" + s[2:]
print(s, t)
print(t[::-1][0] + t[0])Output
hello hallo oh
Fix the bug
This should print the last letter of the word. It crashes.
The program prints the lines below. Your program must print exactly these lines.
Example run
w
Output
The length of the word is 6. What is the largest legal index?
Use the index that always means the last character, or subtract 1 from the length.
word = "window"
print(word[-1])The last index is one less than the length. word[-1] is the simplest fix.
word = "window"
print(word[-1])Output
w
Fix the bug
This should print the first three letters, win. It prints wi.
The program prints the lines below. Your program must print exactly these lines.
Example run
win
Output
The slice stops before the stop index, so that character is left out.
The length of a slice is stop - start. Which stop gives three characters?
word = "window"
print(word[:3])stop is left out, so the first three characters are word[0:3], or simply word[:3].
word = "window"
print(word[:3])Output
win
Fix the bug
This should print the middle character of a word with an odd number of letters. It crashes.
The program prints the lines below. Your program must print exactly these lines.
Example run
p
Output
Read the error message: an index must be an integer. What type does / always give?
Use the division operator that gives a whole number.
word = "paper"
print(word[len(word) // 2])/ gives a float. Use //.
word = "paper"
print(word[len(word) // 2])Output
p
Fix the bug
This should turn "cat" into "hat". It crashes.
The program prints the lines below. Your program must print exactly these lines.
Example run
hat
Output
Square brackets can read a character of a string, but they cannot write one.
Build a new string: the new first letter, joined to everything except the first character of the old word.
word = "cat"
word = "h" + word[1:]
print(word)Build a new string instead of assigning to an index.
word = "cat"
word = "h" + word[1:]
print(word)Output
hat
Fix the bug
This should print the letter at the position the user asks for. It crashes.
With the reply 2, the program prints the lines below. Your program must print exactly these lines.
Example run
a
Output
What type of value does input() give back?
Convert the reply with int() before you use it as an index.
word = "planet"
position = int(input("Which position? "))
print(word[position])input gives text, and an index must be an integer.
word = "planet"
position = int(input("Which position? "))
print(word[position])Output
Which position? 2 a
Write code · Easy
Initials. Store a first name and a last name, and print the two initials with dots, such as M.T.
Use the first name Maya and the last name Tanaka. Print one line: the two initials, each followed by a dot, with no spaces.
The program prints the lines below. Your program must print exactly these lines.
Example run
M.T.
Output
The initial of a name is its character at index 0.
Join four pieces with +: an initial, a dot, the other initial, a dot.
first = "Maya"
last = "Tanaka"
print(first[0] + "." + last[0] + ".")first = "Maya"
last = "Tanaka"
print(first[0] + "." + last[0] + ".")Output
M.T.
Write code · Easy
First and last. Ask for a word and print its first character, its last character, and the word without those two.
Print three lines: the first character, then the last character, then the word without those two.
With the reply string, the program prints the lines below. Your program must print exactly these lines.
Example run
s g trin
Output
The first character is at index 0 and the last one is at index -1.
A slice from post 1 to post -1 leaves out one character at each end.
word = input("A word: ")
print(word[0])
print(word[-1])
print(word[1:-1])word = input("A word: ")
print(word[0])
print(word[-1])
print(word[1:-1])Output
A word: string s g trin
Write code · Easy
Last four. Ask for a phone number as text and print only its last four characters.
Print one line with only the last four characters. If the reply is shorter than four characters, print all of it.
With the reply 5550142907, the program prints the lines below. Your program must print exactly these lines.
Example run
2907
Output
Which slice means "the last n characters"?
A slice is trimmed when the string is too short, so it never raises an error.
phone = input("Phone number: ")
print(phone[-4:])A slice is used so that a number shorter than four characters does not cause an error.
phone = input("Phone number: ")
print(phone[-4:])Output
Phone number: 5550142907 2907
Write code · Medium
Swap the halves. Ask for a word and print it with its two halves swapped: notebook becomes booknote. For a word with an odd length, the first half is the shorter one.
Print one line: the second half followed by the first half.
With the reply notebook, the program prints the lines below. Your program must print exactly these lines.
Example run
booknote
Output
Find the middle post with len(word) // 2.
Cut the word in two at that post and join the two pieces in the opposite order.
word = input("A word: ")
middle = len(word) // 2
print(word[middle:] + word[:middle])Cut at the middle post and join the halves the other way round.
word = input("A word: ")
middle = len(word) // 2
print(word[middle:] + word[:middle])Output
A word: notebook booknote
Write code · Medium
Palindrome test. Ask for a word and print True if it reads the same forwards and backwards.
Print one line: True or False.
With the reply racecar, the program prints the lines below. Your program must print exactly these lines.
Example run
True
Output
Which slice gives a string reversed?
A comparison with == gives True or False. Print the result of the comparison.
word = input("A word: ")
print(word == word[::-1])word = input("A word: ")
print(word == word[::-1])Output
A word: racecar True
Write code · Medium
Capital in the middle. Given word = "python" and an index i, print the word with the character at i replaced by "*". Test with i = 0, i = 3 and i = 5.
Print three lines: the result for i = 0, then for i = 3, then for i = 5.
The program prints the lines below. Your program must print exactly these lines.
Example run
*ython pyt*on pytho*
Output
Take everything before index i, then the star, then everything after index i.
The piece after index i starts at i + 1. Give i a new value and repeat the same print line.
word = "python"
i = 0
print(word[:i] + "*" + word[i + 1:])
i = 3
print(word[:i] + "*" + word[i + 1:])
i = 5
print(word[:i] + "*" + word[i + 1:])The pattern word[:i] + new + word[i + 1:] works at every position, including both ends, because slices past the edge are simply empty.
word = "python"
i = 0
print(word[:i] + "*" + word[i + 1:])
i = 3
print(word[:i] + "*" + word[i + 1:])
i = 5
print(word[:i] + "*" + word[i + 1:])Output
*ython pyt*on pytho*
Write code · Hard
Date untangler. A date is stored as the text "2026-11-23". Using slices and int(), print it in the form 23.11.2026, and then print how many days are left in that month, assuming it has 30 days.
Print two lines: the date with dots, then Days left: followed by one space and the number.
The program prints the lines below. Your program must print exactly these lines.
Example run
23.11.2026 Days left: 7
Output
Count the posts: the year is the first four characters, the month lies between post 5 and post 7, and the day is the last two characters.
Convert each piece with int(). An f-string can put the three numbers and the dots on one line.
date = "2026-11-23"
year = int(date[:4])
month = int(date[5:7])
day = int(date[-2:])
print(f"{day}.{month}.{year}")
print("Days left:", 30 - day)date = "2026-11-23"
year = int(date[:4])
month = int(date[5:7])
day = int(date[-2:])
print(f"{day}.{month}.{year}")
print("Days left:", 30 - day)Output
23.11.2026 Days left: 7
Write code · Hard
Pick and mix. Take two strings such as "abcd" and "1234". Using only slices with a step and +, build a new string from the characters at even indexes of the first string followed by the characters at odd indexes of the second ("ac24"). Print it, and then print its reverse.
Use the two strings from the example. Print the new string first, then its reverse on a second line.
The program prints the lines below. Your program must print exactly these lines.
Example run
ac24 42ca
Output
A step of 2 takes every second character. The even indexes start at 0 and the odd indexes start at 1.
Store the joined string in a variable, so that you can print it and then print it reversed.
first = "abcd"
second = "1234"
mixed = first[::2] + second[1::2]
print(mixed)
print(mixed[::-1])first = "abcd"
second = "1234"
mixed = first[::2] + second[1::2]
print(mixed)
print(mixed[::-1])Output
ac24 42ca
Write code · Hard
Mirror. Ask for a word and print a mirrored version in which the last letter is not doubled: abc becomes abcba.
Print one line: the word followed by its mirror image, with the last letter written only once.
With the reply level, the program prints the lines below. Your program must print exactly these lines.
Example run
levelevel
Output
word[:-1] is everything except the last character. A piece can be reversed with a second pair of square brackets.
you need the reverse of everything except the last character.
word = input("A word: ")
print(word + word[:-1][::-1])word[:-1] is everything except the last character. Reverse that and put it after the word.
word = input("A word: ")
print(word + word[:-1][::-1])Output
A word: abc abcba
A neater form of the same thing is word + word[-2::-1]: start one before the end and walk backwards.
Project
Make a library card. A library builds a short card code from the details of each new member. Write a program that asks three questions, in this order:
2026-03-09 (year, month, day)Then print four lines, with exactly these labels and one space after each colon:
Code: then the card code. The card code is the first three characters of the last name, then the first character of the first name, then the last two digits of the year.Joined: then the date in the form day/month/year. The day and the month are shown as numbers, so a zero at the front disappears.Check: then the card code reversed.Hidden: then the first character of the last name, followed by one star for every other character of the last name.Count posts before you write the slices, as section 8.12 did, and store the card code in a variable so that you can use it two times.
With the replies Maya then Tanaka then 2026-03-09, the program prints the lines below. Your program must print exactly these lines.
Example run
Code: TanM26 Joined: 9/3/2026 Check: 62MnaT Hidden: T*****
Output
The date has a fixed layout: the year lies between post 0 and post 4, the month between post 5 and post 7, and the day is the last two characters. The last two digits of the year lie between post 2 and post 4.
Build the card code with + from two slices and one index. Convert the year, the month and the day with int() before you print the date.
The reversed code is the code with the slice [::-1]. For the last line, repeat a star len(last) - 1 times and put the first character of the last name in front.
first = input("First name: ")
last = input("Last name: ")
date = input("Date of joining: ")
code = last[:3] + first[0] + date[2:4]
year = int(date[:4])
month = int(date[5:7])
day = int(date[-2:])
print(f"Code: {code}")
print(f"Joined: {day}/{month}/{year}")
print(f"Check: {code[::-1]}")
print("Hidden: " + last[0] + "*" * (len(last) - 1))Every piece sits at a fixed place, so slices can take the text apart. int() turns the pieces that are real numbers into numbers, and +, * and an f-string build the new lines.