…
…
Python Programming Fundamentals · Lesson 21 / 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.
Corner Café has started taking online orders, but customers fill in the form carelessly: one writes " Latte : 2 ", another writes "TEA:3". The register wants to see every line in one format, like 2 x latte. Instead of fixing the incoming lines by hand, Ada wants a function that does the job.
In lesson 20 you learned to take any character or piece of a string with an index and a slice. But a slice works when the format of the string is fixed. The format of the lines coming from the online order form is not fixed: some customers put a space at the start, some write everything in capital letters, some leave spaces on both sides of the colon. If you try to cut these lines with slices, you need a separate slice for every customer. Instead, we will use the ready-made tools that come with the string itself. At the end of the lesson, the parse_line function you write will turn three messy lines into this format:
Output2 x latte
3 x tea
1 x brownieIn this lesson you will be able to:
Most of the tools you have used so far were functions: len(product), int(quantity), round(amount, 2). You give a function its value inside the parentheses. Strings also have tools of their own. These tools belong to the string and are called by putting a decimal point after it: product.upper(). These functions attached to a value are called methods. Let's see the difference between the two on one line: len(product) is a function, and it takes the string inside; product.upper() is a method, and it works on the string product. A method is still a function in the end: it has parentheses, it takes extra information inside them if needed, and it returns a result.
Why is there a separate way of writing it? Because these tools only make sense for strings. There is no "convert to uppercase" job for numbers. So Python attaches string-specific jobs to the string itself: when you put the decimal point, you are saying "do this job on this string." All the methods we will use in this lesson are in the table below. You do not need to memorize them now; we will open each one during the lesson. Think of the table as a map.
| Method | What it does | Example | Result |
|---|---|---|---|
strip() | Removes spaces at the start and end | " tea ".strip() | 'tea' |
lower() | Converts to lowercase | "LATTE".lower() | 'latte' |
upper() | Converts to uppercase | "latte".upper() | 'LATTE' |
replace(a, b) | Replaces every a piece with b | "LAT_085".replace("_", "-") | 'LAT-085' |
Using the table, match the expressions below with their results. Two results have been added as extras; one of them is not a result but an error.
Match each expression with the result it produces.
For each row, pick its match from the list, then check.
" latte ".strip()"latte".upper()"latte".replace("t", "k")"latte".find("t")"latte".count("e")"latte,tea".split(",")"latte".index("x")Now let's come to the most important property of methods. In lesson 20 you saw that strings are immutable: you cannot change a character of a string in place, you can only build a new string. Methods follow this rule too. strip(), lower(), upper(), and replace() do not change the string in your hand; they return a new string with the job done. The rule we gave for round in lesson 5 applies here as well: if you do not hand the result of a function to something, it is lost. When the line order.strip() is written on its own, Python produces the new string without spaces, but since that string is not bound to any name, it is lost right away and order stays as it was. If you want to use the result, you bind it to a name: order = order.strip(). This line says "take the cleaned copy, and from now on bind the name order to it."
Example 1 (case): Cleaning the input
A customer wrote the product name with spaces and in capital letters. We clean it and compare the lengths before and after.
order = " LATTE " clean = order.strip().lower() print(clean) print(len(order), len(clean))
Outputlatte
9 5order is still 9 characters: two spaces, five letters, two spaces. The cleaned string sits as a separate string named clean, and it is 5 characters. A copy was made; the original string was not touched.
Now test how much this rule goes against your intuition.
What does this code print?
name = "latte" name.upper() print(name)
Look again at the line order.strip().lower() in Example 1: two methods are written one after the other. This is called chaining. A chain is read from left to right: first order.strip() runs and produces the string 'LATTE'; then .lower() works on this new string and produces 'latte'. Each link takes the result of the one before it. When you build a chain, you need to think about the order. For example, if you want to turn the underscore in a product name into a space and then remove the spaces at the edges, replace comes first and strip second; if you do it the other way around, the new spaces that replace produced may stay there without being removed. A very long chain is hard to read; after three links, it is clearer to give the in-between results a name.
The cleaning methods produce a new string. There are also methods that ask a question about a string; they return an answer, not a string. At the register these questions are asked all the time: "Does the product code start with LAT?", "Is the quantity field only digits?", "How many times does no sugar appear in the note?". The type of the answer changes with the type of the question.
startswith and endswith ask whether a string starts or ends with a certain piece, and return True or False. isdigit asks whether all the characters of the string are digits: "85".isdigit() gives True, but "8.5".isdigit() and " 85".isdigit() give False, because neither the decimal point nor the space is a digit. This is an easy way to check "can it be converted?" before turning the quantity field into a number with int().
find gives the position where the wanted piece appears first in the string; the position is the index from lesson 20, so it is counted from 0. If the piece is not there at all, find does not raise an error, it returns -1. Since -1 cannot be a position, it is a safe way to say "not found." index does the same job; the only difference is that when it finds nothing it raises ValueError: substring not found. If the piece must definitely be there and you want the program to stop if it is not, you use index; if its absence is a normal situation, you use find. count counts how many times the piece appears and returns an integer.
Example 2 (case): Querying the product code
We try the question-asking methods and replace on the product code from lesson 20.
code = "LAT-425-S" print(code.startswith("LAT")) print(code.find("-")) print(code.find("X")) print(code.count("-")) print(code.replace("-", "/")) print(code[4:7].isdigit())
OutputTrue
3
-1
2
LAT/425/S
Truefind("-") gave 3: the first dash is at index 3, and it never looked at the second one. find("X") gave -1, because there is no X in the code. count("-") counted both dashes. replace replaced every dash and returned a new string. In the last line we combined a slice with a method: first we took the piece '425' with code[4:7], then we asked this piece "is it only digits?".
What find returns for a piece it cannot find is the most commonly confused point. Predict.
What does this code print?
code = "LAT-425-S" print(code.find("X"))
With this many tools in your hand, the real skill is choosing the right one. The question itself tells you which tool to use:
| Question | Tool | What it returns |
|---|---|---|
| Does it appear inside? | in (lesson 6) | True / False |
| Where? | find | position or -1 |
| It must be there, stop if not | index | position or error |
| How many? | count | integer |
| Does it start / end like this? | startswith / endswith | True / False |
| Is it only digits? | isdigit | True |
find or count can also be used for "is it there?", but in is both the shortest and the most readable way. If you write order_note.find("no sugar") and try to read the result as true/false, you fall into a trap: if the note starts with no sugar, find returns 0, and you may take 0 to mean "missing." Ask the question with the tool that matches the question.
Below are situations that come up at the register. Match each situation with the method that fits it; two methods have been added as extras.
Which method for each situation?
For each row, pick its match from the list, then check.
LAT?no sugar appear in the note?split and joinAn order note can contain more than one product: "latte, cookie ,tea". The register needs to see each product separately. Since the length of the product names changes, a slice does not work; but what separates the products is clear: the comma. The split method cuts the string at the separator you give it and returns the parts, in order, inside square brackets: "latte,tea".split(",") gives ['latte', 'tea']. The separator itself does not enter the parts; the commas are thrown away.
Example 3 (case): Splitting and cleaning each part
text = "latte, cookie ,tea" parts = text.split(",") print(parts) for part in parts: print(part.strip()) print(" + ".join("latte,cookie,tea".split(",")))
Output['latte', ' cookie ', 'tea']
latte
cookie
tea
latte + cookie + teaLook carefully at the first line: the part ' cookie ' still has a space on both sides. split only throws away the comma; it does not touch the spaces around the comma. That is why we walked through the parts one by one with for and applied strip() to each of them separately. "Split, then clean each part" is the pattern that will be most useful to you in this lesson.
Follow the code below step by step. Notice that a new string is created on every line, while the order box never changes from start to finish.
Run the code line by line: see which line runs next, the variable boxes and the output.
order = " Latte, Tea ,Brownie " clean = order.strip().lower() parts = clean.split(",") print(parts) print(clean.count("a"))
strip removed only the spaces on the outer edges of the string; the spaces of the part ' tea ' were inside the string, so they are still there after split. The count("a") on the last line gave 2: one in latte, one in tea.
What the separator is and what surrounds it changes the result completely. Change the value of text below and each time look at the parts and the number of parts. Pay special attention to what happens with the last value.
When text changes, what does split(",") give, and how many parts come out?
Pick a value; predict the output first, then look.
1text = "latte,tea"2parts = text.split(",")3print(parts)4print(len(parts))
['latte', 'tea'] 2
Faded lines didn't run with this value. The spaces next to the comma stay in the parts; split(",") does not clean spaces, so each part needs its own strip(). If there is no comma in the string (it was written with a semicolon), there is no place to split and the whole string comes back as one part. Joining the separators first with replace(";", ",") solves this problem.
If you give split no separator at all, a different rule applies: the string is split at spaces, extra spaces in a row count as a single space, and spaces at the start and end are ignored. " 2 latte ".split() gives ['2', 'latte']; no empty part appears. When you want to separate words, split() without a separator is the cleanest way.
The opposite of splitting is joining. join combines the parts into a single string, but the way it is written looks backwards at first glance: the method is called not on the parts but on the separator. " + ".join(parts) means "join the parts, putting + between them." The last line of Example 3 first split the string at the comma, then joined the parts with + . The separator goes only between the parts; it is not added at the very start or the very end.
One more warning: count is the tool for the question "how many?", but it counts every piece that appears inside the string and does not look at product boundaries. "iced latte, latte".count("latte") gives 2; but the customer asked for one iced latte and one latte, so there is only 1 latte order. If you want to count products, first split with split, then clean each part and compare it with ==, and count with the counter pattern from lesson 12. count is reliable for counting a letter or a mark, but not for counting things like products that have boundaries.
Now you have all the tools for the job in the case. It is hard to think about a big cleanup in one go; if you divide it into small steps, each step is solved by a single method. Let's take the line " Latte : 2 ". The product name and the quantity are separated by a colon, so first we split the line at the : character and get two parts: ' Latte ' and ' 2 '. The first part is the product name; we remove its spaces and convert it to lowercase. The second part is the quantity; we convert it to a number with int(). int() ignores spaces at the start and end by itself, so int(" 2 ") gives 2 without a problem. Finally, we build the line the register expects with an f-string and return it with return. As you have known since lesson 14, we put a repeated job into a function; and we name each step with a comment line.
Example 4 (case): A function that parses an order line
def parse_line(line): # 1. Split the line at the ":" character parts = line.split(":") # 2. Clean the name, convert it to lowercase name = parts[0].strip().lower() # 3. Convert the quantity to a number quantity = int(parts[1]) return f"{quantity} x {name}" print(parse_line(" Latte : 2 ")) print(parse_line("TEA:3")) print(parse_line("Brownie :1"))
Output2 x latte
3 x tea
1 x brownieThree lines arrived in three different formats, and the function turned all three into the same format. parts[0] is the first part of the split and parts[1] is the second part; the square brackets work the same way as the index in lesson 20.
Now develop the function yourself. Some customers use a semicolon instead of a colon: Latte;2. First run the cell as it is. Then delete the # character in the comment line and run it again: you get IndexError: list index out of range, meaning "list index outside the range." Since split(":") found no place to split at the semicolon, it returned a single part, and there is no part parts[1]. Your task: at the start of the function, before the split, add a single line that turns the semicolon into a colon. Then see that the input " hot chocolate : 1" on the last line also works correctly.
Try it now· not graded; doesn't affect progress
Sometimes the register wants only the product name. Below, the lines of a short function that does this are mixed up. Each line uses the result of the one before it; put the lines in the right order.
Build the function that returns only the product name from a line, and try it.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
String methods are not special to the café; the same problems come up in every form that people fill in by hand. A student club asks for an email address on its membership form and accepts only campus addresses. Students write the address with spaces and in mixed uppercase. What needs to be done is very similar to the café: clean first, then ask the right questions.
Example 5 (outside the case): Cleaning and querying an email address
email = " Maya.Lopez@Campus.EDU " clean = email.strip().lower() print(clean) position = clean.find("@") print(clean[:position]) print(clean.endswith(".edu")) print(clean.split("@"))
Outputmaya.lopez@campus.edu
maya.lopez
True
['maya.lopez', 'campus.edu']find("@") gave the position of the mark; the slice up to that position is the username. endswith(".edu") answered the question "is it a campus address?". split("@") did the same job in another way: it split the address into the two parts on either side of the mark. The same result can be reached in more than one way; which one is more readable is up to you.
lower() and upper() do not always work letter by letter the way you might expect. Accented letters convert without a problem: "Café".upper() gives 'CAFÉ' and "CAFÉ".lower() gives 'café'. But a few letters follow different rules. The German letter ß has no single capital letter, so upper() turns it into two letters: "Straße".upper() gives 'STRASSE'. The string was 6 characters long and became 7.
What does this code print?
print("Straße".upper())
This causes a trap when comparing: "Straße".lower() gives 'straße' and "STRASSE".lower() gives 'strasse', so the two are not equal even though they are the same word. For comparisons that ignore case, Python has a stronger method called casefold(): "Straße".casefold() gives 'strasse'. For product names like latte, tea, and brownie, strip().lower() is enough. When you compare names of places or people that may contain letters like ß, use casefold().
The error you will see most often when working with methods is AttributeError, an "attribute error." What Python is saying is: "this value has no such attribute, no such method." This error comes in two ways. The first is writing the name of the method wrong. If you write "latte".uper(), Python 3.14 tells you this:
OutputAttributeError: 'str' object has no attribute 'uper'. Did you mean: 'upper'?The first part of the message says "the string (str) object has no attribute called uper." The Did you mean: 'upper'? part at the end asks "did you mean upper?". Read Python's suggestion; most of the time it tells you the fix directly. This suggestion may not appear in some Python versions, but the first part is always the same.
The second is calling the method on a value of the wrong type. String methods exist only on strings.
It is easy to make this mistake in the function in Example 4: after the line quantity = int(parts[1]), quantity is now a number. If you write quantity.strip() on it, you get 'int' object has no attribute 'strip'. You do the cleaning before converting to a number, while it is still a string.
In the Caesar cipher project at the end of the unit, every letter will be shifted a few steps forward along the alphabet. find gives the position of a letter in the alphabet, and the square brackets give the letter at that position. To wrap around to the start when we reach the end of the alphabet, we use the % operation from lesson 3.
alphabet = "abcdefghijklmnopqrstuvwxyz" print(len(alphabet)) position = alphabet.find("z") shifted = alphabet[(position + 3) % len(alphabet)] print(position, shifted)
Output26
25 cz is the last letter, and its position is 25. Going three steps forward makes it 28; there is no position 28 in the alphabet, but 28 % 26 gives 2. The letter at position 2 is c, so the shift wrapped around to the start and continued.
In a homework form, we want to find how many words are in the description a student wrote. The student sometimes left two or three spaces between words. Since split() without a separator ignores the extra spaces, it separates the words cleanly; and join joins the words back together with a single space.
sentence = words = sentence.split() (words) ((words)) (.join(words))
Not binding the result of a method. You want to remove the spaces of a name:
name = " corner " name.strip() print(name)
On the screen you see corner with its spaces, and Python raises no error. Why? strip() returned a new cleaned string, but the second line did not bind that string to any name, so the copy was lost; name is still bound to the old string. The fix is to bind the result to the same name: name = name.strip(). The same rule applies to lower, upper, and replace. When you call a method and do not use the result, stop and ask: "where is the string it returned going?"
This mistake is not always silent; the lost result comes back as an error on a later line. From a receipt you have the string "$4.25", and you want to remove the dollar sign and turn the price into a number:
price = "$4.25" price.replace("$", "") print(float(price) * 2)
OutputTraceback (most recent call last):
File "<code>", line 3, in <module>
print(float(price) * 2)
~~~~~^^^^^^^
ValueError: could not convert string to float: '$4.25'line.strip()); since strings do not change, strip, lower, upper, and replace return a new string, so bind the result to a name (name = name.strip()).in, where find (-1 if missing; index raises an error), how many count, does it start/end like this startswith/endswith, is it only digits isdigit; to count products, split and compare instead of using count.split(separator) does not clean spaces, so apply strip() to each part; separator.join(parts) joins only strings, so convert a number with str() first.Next lesson: Now we will show the cleaned lines neatly aligned on the receipt: formatting.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
startswith(p) / endswith(p) | Does it start / end with this piece? | "LAT-085".startswith("LAT") | True |
isdigit() | Are all the characters digits? | "085".isdigit() | True |
find(p) | First position of the piece; -1 if missing | "latte".find("t") | 2 |
index(p) | First position of the piece; error if missing | "latte".index("t") | 2 |
count(p) | How many times does the piece appear? | "latte".count("t") | 2 |
split(separator) | Splits the string into parts | "a,b".split(",") | ['a', 'b'] |
separator.join(parts) | Joins the parts with the separator | "-".join(["a", "b"]) | 'a-b' |
FalseOutput['today', 'the', 'café', 'was', 'very', 'busy']
6
today the café was very busyThe error appears on line 3, but remember from lesson 17: the place where you see it and the cause are often different. The '$4.25' at the end of the message gives the clue: the string going into float() still has the dollar sign. So the replace on line 2 did its job, but its result was not bound to any name. The fix is on line 2: price = price.replace("$", ""). With this change the program prints 8.5.