Python Arena
Step 5 of 6

Slices

An index gives you one character. A slice gives you a piece of a string, a substring: text[start:end] takes the characters from the index start up to, but not including, the index end.

text = "basketball"
print(text[0:6])
print(text[6:10])
print(text[2:5])
Output
basket
ball
ske

It helps to picture the indexes as marks between the characters, with the mark 0 before the first character. A slice takes what lies between two marks:

| b | a | s | k | e | t | b | a | l | l |
0   1   2   3   4   5   6   7   8   9   10

So text[0:6] is everything between the marks 0 and 6. Because the end is left out, the length of a slice is simply end - start: text[2:5] has 3 characters.

Leaving out the start or the end

Leave out the start, and the slice begins at the start of the string. Leave out the end, and it goes on to the end. Negative indexes work in slices too:

date = "2026-10-15"
print(date[:4])
print(date[5:7])
print(date[-2:])
Output
2026
10
15

date[:4] is the first four characters, and date[-2:] the last two.

Slices don't run out

Unlike an index, a slice that goes past the end of the string doesn't stop the program. It takes whatever characters there are, perhaps none at all:

word = "cat"
print(word[1:100])
print("[" + word[5:9] + "]")
Output
at
[]

A loop can move a slice along a string. This one prints a code in pieces of three characters; the last piece is shorter, since the slice stops at the end of the string:

code = "ABCDEFGH"
start = 0
while start < len(code):
    print(code[start:start + 3])
    start += 3
Output
ABC
DEF
GH

Your task

Challenge 1 of 3

Fill in the slices so the program prints the hours, the minutes and the seconds of the time.

Hours: 14
Minutes: 35
Seconds: 20

Challenge 2

Write a program that asks for a card number and prints it with every character except the last four replaced by *. The number always has at least four characters.

Card number: 1234567812345678
************5678

Challenge 3

Write a program that asks for a word and prints it smaller and smaller: each line drops one character from both ends and is moved one space to the right, as long as there are characters left.

Word: abcdefg
abcdefg
 bcdef
  cde
   d