…
…
Python Programming Fundamentals · Lesson 20 / 40 · Strings
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
In Corner Café's new register system, every product has a code: LAT-425-S. The first three letters show the product, the three digits in the middle show the price in cents, and the last letter shows the cup size. Ada does not want the cashier to read this information by eye every time; she wants the register to see the code and find the product, the price, and the size by itself.
So far you have used strings as a whole: you printed them, joined them with +, measured them with len(), and in lesson 10 you walked through their characters one by one with for letter in code:. But the register's job is different: it does not want the whole code, it wants the character at one place or the piece at one place. You need to be able to say "give me three characters, starting from the fifth." The read_code function you will write at the end of the lesson will print this for two codes of different lengths:
OutputLAT | $4.25 | Small
MOCH | $4.75 | MediumIn this lesson you will be able to:
A string is an ordered sequence of characters placed side by side. Letters, digits, dashes, spaces: all of them are characters, and each one has a place in the sequence. This place is called an index. To reach a character, you open square brackets right after the name of the string and write the index: code[0]. Here is where students get stuck most: Python starts counting not from 1 but from 0. The index of the first character is 0, the second is 1, the third is 2.
The table below shows each character of the code LAT-425-S with its index underneath. We will explain the negative indexes in the third row in a moment.
| Character | L | A | T | - | 4 | 2 | 5 | - | S |
|---|---|---|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| Negative index | -9 | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
Look at the table carefully. The code has 9 characters, but the index of the last character is 8. Because counting starts from 0, the numbers are always one behind: last index = length - 1. This "one less" relation is confusing at first, but it sticks once you write the table yourself.
Now imagine you do not know the length. Codes of 9 characters and of 10 characters will arrive at the register, and every time you want the last character, the size. Calculating the length and subtracting one works, but it is clumsy. Python gives a negative index for this: a negative index counts from the end. code[-1] is the last character, code[-2] is the second to last. Whatever the length of the string, [-1] always gives the last character. Negative counting starts not from 0 but from -1, because there is no such number as -0 that is different from 0.
Example 1 (case): Single characters
code = "LAT-425-S" print(code[0]) print(code[-1]) print(len(code))
OutputL
S
9code[0] gave the first character and code[-1] gave the last. len(code) said 9, so the largest positive index is 8. What you take with an index is again a string: a string of one character.
Now test how much counting from 0 goes against your instinct.
What does this code print?
code = "LAT-425-S" print(code[1])
Below, change the value of i and see which character comes each time. Compare 8 and 9 especially: in a string of 9 characters there is no seat number 9.
Which character does code[i] give as i changes?
Pick a value; predict the output first, then look.
1code = "LAT-425-S"2i = 03print(code[i])
L
Faded lines didn't run with this value. The character at index 4 is the digit 4 (the dash is at index 3). 8 and -1 give the same character, the last letter S. The largest index of a string of 9 characters is 8, so when you write 9, Python raises IndexError: string index out of range.
Let us also make clear the difference between an index and the for letter in code: loop from lesson 10. for letter in code: gives you the characters in order, but it does not answer the question "which number is this character?" An index answers exactly this question. It is possible to combine the two: range(len(code)) counts from 0 to one less than the length, so it produces exactly the valid indexes. Follow the code below step by step and watch how the i box goes from 0 to 8 and which character code[i] brings at each step. range never reaches 9, so the loop never raises IndexError. If you like, change the code to your own product code and trace it again.
Run the code line by line: see which line runs next, the variable boxes and the output.
code = "TEA-125-M" for i in range(len(code)): print(i, code[i])
A single character is enough for the size, but the price is made of three characters: 425. You could take the three characters one by one and stick them together with +, but there is a shorter way: a slice. You take a slice by writing two numbers separated by a colon inside the square brackets: code[start:end]. The rule is: the start is included, the end is not. code[4:7] takes indexes 4, 5, and 6, stops at index 7 and does not take it. The result is 425.
The fact that the end is not included looks like an unnecessary rule at first, but it makes your job easier: the length of a slice is always end - start. code[4:7] is 7 - 4 = 3 characters. If you want a piece of three characters, the end is the start plus three.
Both ends of a slice can be left empty. If the start is empty, the slice begins at the beginning: code[:3] gives the first three characters, LAT. If the end is empty, it goes to the end: code[4:] gives 425-S, everything from index 4 to the end. You can write a negative number at the ends too: code[-2:] means "from the second to last to the end" and gives -S.
A slice has an important difference from a single index: a slice that runs past the end does not raise an error. While code[9] raises an error, code[5:100] works without trouble and gives 25-S. A slice says "give me whatever is from here to there"; if the string does not go as far as 100, it gives what there is. If the start passes the end, there is no error either, and the result is an empty string: code[8:3] takes no characters. A single index asks for one particular seat; if that seat does not exist, there is nothing to give, so it raises an error.
A third number can be added to a slice too: the step. code[::2] goes from start to end taking every second character, and code[::-1] goes from the end to the start and reverses the string. You will hardly need the step at the register, but it is enough to know it so that you recognize it when you see it.
One last important point: the result of a slice is again a string. code[4:7] gives you not the number 425 but the string "425". To calculate with the price, you need to turn it into a number with int(), which you learned in lesson 4.
Example 2 (case): Splitting the code into parts
code = "LAT-425-S" product = code[:3] price_cents = int(code[4:7]) size = code[-1] print(product, price_cents, size)
OutputLAT 425 SThe price is in cents: 425 cents is $4.25. If a code has a leading zero, such as 075, int("075") drops it and gives 75. Now you can add and multiply with price_cents.
Example 3 (outside the case): Day name and date
A slice is useful not only for product codes but for every string with a fixed format. First let us try the three kinds of slice with a day name, then turn a date into the month/day/year format.
day = "Monday" print(day[:3]) print(day[::2]) print(day[::-1]) date = "2026-03-25" print(f"{date[5:7]}/{date[8:]}/{date[:4]}")
OutputMon
Mna
yadnoM
03/25/2026In the date string, the year sits at indexes 0–3, the month at 5–6, and the day at 8–9; the dashes are at 4 and 7. For the year the end is 4 and for the month it is 7, because the end is not included.
If you have trouble writing a slice, use this method: write the characters of the string side by side on paper and put its index under each one. The index of the first character of the piece you want is the start; one more than the index of its last character is the end. This method prevents most "one less, one more" mistakes before you write the code.
Now test whether you have really taken in that the end is not included.
What does this code print?
code = "LAT-425-M" print(code[4:7])
Below you can change two values together: the start of the slice (start) and its end (end). Try all nine combinations. Notice that the length on the second line is end - start each time, and that when the start passes the end, no character is left on the first line.
Change the start and the end: what does the slice give, and how many characters does it take?
Pick a value; predict the output first, then look.
1code = "LAT-425-S"2start = 03end = 34print("Slice:", code[start:end])5print("Length:", len(code[start:end]))
Slice: LAT Length: 3
Faded lines didn't run with this value. The length is always end - start: 3 characters from 4 to 7, 5 characters from 4 to 9. When the start passes the end (4-3, 8-3, 8-7), the slice gives an empty string and no error occurs. From 8 to 9, only the last character, S, is left.
Now try all the kinds of slice together on the same code. Match each expression with the result it gives; two results have been added as extras. One of the pairs is not a result but an error.
What does each expression give for code = "LAT-425-S"?
For each row, pick its match from the list, then check.
code[:3]code[4:]code[-2:]code[::-1]code[5:100]code[::2]code[9]The register will do the same job again and again for every product. As you have known since lesson 14, we put a repeated job in a function: the function takes the code as a parameter and gives the piece back with return. The first try for the price looks like this: return int(code[4:7]). It works perfectly for LAT-425-S.
Then Ada adds mocha to the menu, and its code has four letters: MOCH-475-M. This time the same function takes -47 with code[4:7]. The surprising part is this: int("-47") does not raise an error, because it looks like a number with a minus sign; it quietly returns -47. The register would try to sell the mocha for minus 47 cents. Then water comes, with two letters: WA-075-S. This time the slice takes 75-, and because int() cannot turn this into a number, it raises ValueError. A wrong slice sometimes raises an error and sometimes produces a wrong result without a sound. A silent mistake is more dangerous than an error, because nobody notices it.
See this for yourself. In the cell below, the function and two calls are ready. First press Run: the first line prints 425 and the second line prints -47. There is no error, but is -47 right? Then delete the # at the beginning of the last line and run again: the water code raises ValueError: invalid literal for int() with base 10: '75-'. Look at the '75-' string in the error message; the slice cuts the wrong place. Your task: change the slice so that it counts from the end, and all three lines print 425, 475, and 75.
Try it now· not graded; doesn't affect progress
The key to the solution is finding which end of the code is fixed. The product name can have 2, 3, or 4 letters, so counting from the start is not reliable. But the end of the code always has the same format: dash, three digits, dash, one letter. Counting from the end, the digits of the price are always at indexes -5, -4, and -3; the slice is code[-5:-2]. The size is always code[-1]. The product name starts at the beginning and ends before the last six characters (-425-S): code[:-6]. The rule is: in a string of changing length, index from the fixed end. Before writing code, ask yourself "which side of this string never changes?"
Example 4 (case): The function that reads the code
Now we can write the target program of the lesson. The three steps of the function are named with comment lines.
def read_code(code): # 1. Take the parts from the fixed ends product = code[:-6] price_cents = int(code[-5:-2]) letter = code[-1] # 2. Turn the size letter into a name if letter == "S": size = "Small" elif letter == "M": size = "Medium" else: size = "Large" # 3. Return the line return f"{product} | ${price_cents / 100:.2f} | {size}" print(read_code("LAT-425-S")) print(read_code("MOCH-475-M"))
OutputLAT | $4.25 | Small
MOCH | $4.75 | MediumFor MOCH-475-M, code[:-6] leaves out the last six characters -475-M and MOCH remains. The price and the size are read from the same place whatever the length of the code. The second step is the if–elif–else chain from lesson 7; it turns the letter you took with a slice into a name.
How can you be sure that a function like this works correctly? As you saw in lesson 19, by writing small tests with assert. Below, the lines of the price function and its tests are mixed up. First the function must be defined, then it must be tested with codes of two different lengths, and at the very end a message must be printed. Put the lines in the right order.
Define the function, test it with codes of two different lengths, and print the message at the very end.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
One day Ada wants to change the latte code to CAT-425-S; only the first letter will change. The first idea that comes to mind is to assign a new value to that letter with an index. First predict the result.
What does this code do?
code = "LAT-425-S" code[0] = "C" print(code)
Strings are immutable objects: once a string is created, its characters cannot be changed in place. The line code[0] = "C" raises TypeError: 'str' object does not support item assignment. What the error message says is: the string type (str) does not support assigning to one of its items (item). So how do we "change" a string? We do not; we build again the string we want with slices and +: code = "C" + code[1:]. The right side joins "C" and AT-425-S and produces a brand new string: CAT-425-S. The old string did not change; the name code is now tied to the new string. In lesson 2 we compared a variable to a box: we took the old string out of the box and put the new one in, and we never touched the letters of the old string.
This rule has an important result for functions: a function that works with a string cannot change the string it is given. It builds the new string and gives it back with return. The caller assigns this result to a variable.
Example 5 (outside the case): Hiding a phone number
In the café's loyalty program, a customer's phone number should not be written openly on the receipt. The first 4 and the last 2 digits will show, and the ones in between will be stars.
phone = "5550142877" masked = phone[:4] + "*" * (len(phone) - 6) + phone[-2:] print(masked)
Output5550****77We joined three parts and built a new string: the first 4 digits, the stars, and the last 2 digits. We did not write the number of stars by hand as 4; we calculated it by subtracting the 6 visible digits from the total length. The string repetition you saw in lesson 4 ("*" * 4) is useful here. Even if the phone number has 7 digits, the code gives the right result without change. The phone string also stays as it is; masked is a separate, new string.
A customer wants to change a small latte to a large one. Everything except the last letter of the code will stay the same. Because a string does not change, we build the new code from the end: everything except the last character, plus the new letter.
code = "LAT-425-S" new_code = code[:-1] + "L" print(code) print(new_code)
OutputLAT-425-S
LAT-425-LWords that stay the same when read backwards, like "level", are called palindromes. We write a function that compares a word with its own reverse, using the reversing slice [::-1]. The result is True or False.
def is_palindrome(word): return word == word[::-1] print(is_palindrome("level")) print(is_palindrome("latte"))
OutputTrue
FalseThinking the index of the last character equals the length. You learned the length, and you want to reach the last character with len:
code = "LAT-425-S" size = code[len(code)]
OutputIndexError: string index out of rangeThe last line of the message says "string index out of range". len(code) is 9, but the indexes of a string of 9 characters go from 0 to 8; there is no seat number 9. The right way is code[-1] (or, the longer way, code[len(code) - 1]). There is also a sneaky sibling: writing the end one less in a slice does not raise an error, it only gives a wrong result. If you write code[0:2] for the product abbreviation, you get LA, not LAT; Python does not warn you. That is why you should test every function that works with slices with assert, using a few different codes.
len(string) - 1; [-1] gives the last character whatever the length, and an index that does not exist raises IndexError.[start:end:step] takes the start and does not take the end; in a string of changing length, count from the fixed end (code[-5:-2]), and a slice that runs past the end does not raise an error.TypeError; build the string you want again with slices and +, and in a function return it with return.Next lesson: Codes do not always arrive in a clean form: spaces at the start, uppercase and lowercase mixed. In the next lesson we will clean them up with the string's ready-made tools.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.