Indexing and slicing · Python from Zero
How do you get a single letter, or a piece, out of a string?
Course contentsWhy you need it
Text is everywhere: names, messages, codes, file names. Very often you need part of it: the first letter for initials, the last 4 digits of a card, the year from a date. Python lets you reach any position with an index, and any piece with a slice.
The intuition
A string is a row of numbered boxes, and numbering starts at 0:
| P | y | t | h | o | n |
|---|---|---|---|---|---|
| 0 | 1 | 2 | 3 | 4 | 5 |
| -6 | -5 | -4 | -3 | -2 | -1 |
word[0]is "P",word[5]is "n". Negative numbers count from the end:word[-1]is "n".len(word)is 6, the number of characters. The last index islen(word) - 1.- A slice
word[start:stop]takes fromstartup to but not includingstop:word[0:2]is "Py". Leave out a side to go to the edge:word[2:]is "thon".
Definition
Index
An index is the position of an item in a sequence; Python indexes start at 0.
Slice
A slice s[start:stop] is a new string containing the characters from index start up to, but not including, index stop.
Examples
Taking pieces
Try it yourselfTry other numbers in the brackets.
word = "Python"
print(word[0], word[-1])
print(word[0:2], word[2:])
print(len(word))- L2Index 0 is the first character; -1 is the last.
P n - L3[0:2] takes indexes 0 and 1 (not 2). [2:] takes from 2 to the end.
Py thon - L4len counts the characters.
6
Joining strings
Try it yourself+ glues strings together; it doesn't add spaces for you.
first = input()
last = input()
print(first + " " + last)
print(first[0] + last[0])Grace Hopper
- L3Three strings joined: first, a space, last.
Grace Hopper - L4The first character of each: the initials.
GH
Common mistakes
Counting from 1
The first character is s[0], not s[1]. s[len(s)] is an IndexError; the last one is s[len(s) - 1] or simply s[-1].
The stop index is not included
s[1:3] has 2 characters (indexes 1 and 2). Length of a slice = stop − start.
Quick quiz
1. What does this print?
s = "hello"
print(s[1])Show the answer
Answer: B
Index 1 is the second character because counting starts at 0.
2. What does this print?
print("abcdef"[2:4] + "!")Show the answer
Answer: A
Indexes 2 and 3 are c and d; 4 is not included.
Practice
3 exercises in three steps: predict what a program prints, change a program to meet a new requirement, then write one from scratch. Your code runs in the browser and is checked the moment you submit.
- PredictSlice the banana
Type exactly what this program prints.
- ModifyFirst, last, length
The program prints the first letter of a word. Make it print three lines: the first letter, the last letter, and the length.
- WriteInitials
Read a first name and then a last name (two lines). Print the initials with dots, like
A.L.for Ada and Lovelace.
Practise this lesson
Open the interactive lesson to edit and run these examples and solve the exercises with instant feedback. Free to start, no sign-up.
Interactive lessons open in order. If you have not done the earlier ones yet, you start at the course map.
Terms in this lesson
| Term | Chinese | Definition |
|---|---|---|
| Index | 下标 | The position of an item in a sequence, starting from 0. |
| Slice | 切片 | A part of a sequence taken with [start:stop], excluding stop. |
| len() | len() 长度函数 | A function that returns the number of items in a sequence. |
| Concatenation | 拼接 | Joining strings end to end with +. |