Chapter 11 — Strings in Depth & Text Processing
The module's primary reading · ~40–50 minutes · Objective 7 (process text with string methods, read and write files with the with statement, and handle runtime errors with try and except by exception type) and Objective 2 (use variables and the core types int, float, str, and bool; evaluate expressions with correct operator precedence, including true division, floor division, and remainder; convert between types; and read input and build output with indexing, slicing, and f-strings) · Read it first this week; the lecture, the slides, the tutorial, the quiz, and the Coding Lab all build on it.
In plain language
Most of the data people care about arrives as text: a line in a log, a typed reply, a message in a group chat. This week you learn the tools Python gives you for working with text. A string method (a small tool that belongs to a piece of text and is called with a dot) can turn text into capitals, trim its ends, or cut it into pieces. Every one of these tools hands you a new piece of text and leaves the old one exactly as it was. As always, you predict what each program prints and then run it to check.
Why you already care about this
A sign-up sheet at a campus club fair asks visitors one question, and the answers pile up. Some wrote "Yes", some wrote "yes", and a few left a space before the word. A person reading the sheet sees a column of yeses at a glance. A program comparing each answer with "yes" sees three different strings, because to a computer a capital Y and an extra space are real characters.
Your reading log has the same problem in a different form. Since Week 3 it has held the book's title as text. This week it holds a whole line of the log, "day 3: 25 pages", and you want the 25 out of it as a number you can add to. The line is one string of 15 characters, and nothing in it is a number yet.
This chapter shows you how to call the string methods and why each one leaves the original alone. You will cut a line into a list, glue a list back into a line, and search a string without getting fooled. Then you will put these tools together into small text programs. It ends by checking a chatbot's claim about strings with a run.
By the end of this chapter you will be able to:
- call the nine core string methods and predict the new value each one hands back;
- spot and fix the forgot-to-reassign bug;
- split a line of the reading log into a list, convert one piece, and join the line back together;
- predict what
split()cuts on, with and without an argument; - read
find()as a position or-1and write a correct test for a match; - count words, count a character, normalize a reply, and reverse a string.
Carry this line with you: a string method hands you a new string; it never changes the old one.
Where we are
- Already covered: Week 3 gave you strings, indexing from 0, slices, and
len(). Week 4 gave youifand truthiness, and Week 6 gave youforloops. Week 7 gave you return values. Week 9 gave you lists and methods, and Week 10 gave you dictionaries, the counting idiom, and the word immutable. - This week: the core string methods, immutability in strings,
split()andjoin(),find()and its-1,replace()andcount(), and small text algorithms. - How they connect: a string method is called like the list methods from Week 9, with a dot after a value. But a string is immutable, so every string method hands back a new value instead of changing anything in place.
- Where we're going next: Week 12, on files and exceptions, reads whole files of lines like the ones you split this week, and handles the errors a bad line can cause.
Three earlier ideas carry most of the weight. From Week 3, positions in a string start at 0, so the first character of "Hello" sits at position 0, and a slice can take a step. From Week 7, a method call is a function call, and its return value is lost unless you store it, print it, or use it. From Week 10, an immutable value cannot be changed after it is made; a tuple was the first example, and a string is the second. Spend extra time on Sections 2 and 5. The quiz leans on both, and so do the files you open next week.
1. Ask a string to do work: methods hand back new values
A copy shop does not touch your original page. You hand over a sheet, ask for it bigger or in bold, and the clerk hands you a fresh copy while your original goes back in your folder unchanged. String methods work like that counter.
A string method is a function that belongs to a string and is called with a dot after it, such as upper in s.upper(); it hands back a new value and never changes the string itself.
You met methods on lists in Week 9, written the same way: a value, a dot, the method's name, and parentheses. The string methods this week are upper, lower, strip, split, join, replace, find, count, and startswith.
Worked example — the method set. This pinned program calls one method per line on the string s = "Hello, World". Predict all eleven lines before you read the output.
s = "Hello, World"
print(s.upper())
print(s.lower())
print(s.split())
print(s.count("l"))
print(s.find("W"))
print(s.find("z"))
print(s.replace("o", "0"))
print(s.startswith("Hello"))
print("-".join(["a", "b", "c"]))
print(" padded ".strip())
print(s)
Output
HELLO, WORLD
hello, world
['Hello,', 'World']
3
7
-1
Hell0, W0rld
True
a-b-c
padded
Hello, World
Here is what each line handed back.
- .upper() is the string method that hands back a new string with every letter turned into a capital letter, leaving digits, spaces, and punctuation as they were. The comma and the space came through unchanged.
- .lower() is the string method that hands back a new string with every letter turned into a small letter, leaving digits, spaces, and punctuation as they were.
split()cut the string at the space and handed back a list of two strings. Section 3 is about it.count("l")found the two l's inHelloand the one inWorld, and 2 + 1 = 3.find("W")handed back a position. Counting from 0, the lettersH,e,l,l,o, the comma, and the space fill positions 0 to 6, soWsits at position 7. Section 5 explains the-1on the next line.replace("o", "0")swapped both small o's for zeros. Section 6 is about it.startswith("Hello")answered a yes-or-no question, so it handed backTrue.joinglued three strings together with a hyphen between each pair.strip()trimmed the spaces off both ends of" padded ".- The last line printed
sitself, and it is stillHello, World.
That last line is the point of the whole section. Eight of those method calls ran on s itself, and s did not change at all. Each method built a new value and handed it to print.
Misconception check. Students often think a method such as
upper()changes the string it is called on, so they expect the last line to printHELLO, WORLDor evenhello, world. That is tempting, because in Week 9appendreally did change the list it was called on. But a string is immutable: no method can change it. The cure: read every string method as "build a new string from this one," and look for where that new string goes.
In practice (your tools). Open your free browser Python runner, paste the method set, and press Run. Then add one line, print(s.upper().lower()), and predict it before you run it. The Standard Library reference's String Methods section on docs.python.org lists every method with what it returns.
Memory hook: a string method is a copy-shop counter; the original goes home unchanged.
2. Keep the new value: the forgot-to-reassign bug
You ask a friend to translate a sign, and they read the translation aloud. If you did not write it down, the sign in your hand is still in the other language. The translation existed for a moment and then it was gone.
The forgot-to-reassign bug is the logic error of calling a string method on a line of its own and expecting the string to change; the new string is lost unless it is assigned back to the name.
Worked example — the pinned forgot-to-reassign program. Predict the one line it prints.
s = "Hello"
s.upper()
print(s)
Output
Hello
Here is the trace.
sgets the stringHello.s.upper()builds the new stringHELLOand hands it back. Nothing stores it, so Python throws it away.print(s)prints the string thatsstill holds:Hello.
The program raised no error, and it printed the wrong thing. That makes it a logic error, the kind only a prediction can catch.
Worked example — the one-line cure. Store the new string in the name.
s = "Hello"
s = s.upper()
print(s)
Output
HELLO
The line s = s.upper() reads from right to left. Python first works out s.upper(), which is HELLO, and then = puts that new string into s. The old Hello was never changed. The name s now points at a different string.
Misconception check. Students often think the line
s.upper()"did nothing," and so they decide the method is broken. That is tempting, because the output looks as if the call never ran. But the call did run and did buildHELLO; the program never kept it. The cure: every string method call needs a home, such ass = s.upper(), aprint(...)around it, or a place in a bigger expression.
Honesty note: you will meet this bug again in Week 12, with lines read from a file, and you will spot it in other people's code too. It is a one-line fix every time.
In practice (your tools). Paste the pinned program into Python Tutor at pythontutor.com and click Next. After the second line, the global frame still shows s holding "Hello". Now paste the cure and step again: after s = s.upper(), s holds a new string, "HELLO".
Memory hook: no home for the new string — no change at all.
3. Take a line apart and rebuild it: split and join
A cashier reading a line on a receipt splits it in their head: a count, an item, a price. Programs do the same thing with split(), and they glue the pieces back together with join().
Whitespace means the characters that show up as blank space when text is printed, such as an ordinary space, a tab, and the line break at the end of a line.
.split() is the string method that cuts a string into pieces and hands back a list of strings; with empty parentheses it cuts on whitespace, and given a separator such as a comma it cuts there instead.
A separator is the piece of text that sits between the parts when strings are joined, or that a string is cut on when it is split, such as a space, a comma, or a hyphen.
.join() is the string method called on a separator that hands back one new string made from a list of strings, with the separator placed between each neighbouring pair.
Worked example — the reading log as text. This is the pinned Week 11 stage of your reading log. One line of the log is a string. Predict all four lines.
entry = "day 3: 25 pages"
parts = entry.split()
print(parts)
pages = int(parts[2])
print(pages + 5)
print(entry.upper())
print(entry)
Output
['day', '3:', '25', 'pages']
30
DAY 3: 25 PAGES
day 3: 25 pages
Here is the trace.
entry.split()cuts the line at each space and hands back a list of four strings:['day', '3:', '25', 'pages']. The colon stays glued to the 3, becausesplit()cut only at spaces.parts[2]is the item at position 2, counting from 0, which is the string'25'. It is text, with quotation marks in the printed list.int(parts[2])turns the text'25'into the number 25, and 25 + 5 = 30.entry.upper()builds a capitalized copy,DAY 3: 25 PAGES.- The last line prints
entryitself, stillday 3: 25 pages.
In words: split() turned one string into a list, int() turned one piece into a number, and the original line was never touched.
Worked example — what each one hands back. Check the types for yourself.
entry = "day 3: 25 pages"
parts = entry.split()
print(type(parts))
print(type(" ".join(parts)))
print(len(parts))
Output
<class 'list'>
<class 'str'>
4
split() makes a list, and join() makes a string. The list holds 4 items, one per word of the line.
Worked example — rebuild the line. Suppose you read 5 more pages on day 3. Put the new count into the list as text, then join the four parts with a space.
entry = "day 3: 25 pages"
parts = entry.split()
parts[2] = str(int(parts[2]) + 5)
new_entry = " ".join(parts)
print(new_entry)
print(entry)
Output
day 3: 30 pages
day 3: 25 pages
Read the third line from the inside out. int(parts[2]) is 25, then 25 + 5 = 30, then str(30) turns the number back into the text '30', and that text goes into position 2 of the list. You can change the list, because a list is mutable. Then " ".join(parts) builds one new string with a space between each pair of parts. The old entry still prints day 3: 25 pages.
Why turn 30 back into text? Because join() glues strings, and only strings. Here is what happens if you leave the number in the list.
parts = ["day", "3:", 30, "pages"]
print(" ".join(parts))
Output
TypeError
The last line of the error names TypeError: one item was a number, not a string, and nothing printed.
Misconception check. Students often think
.split()and.join()both give strings, because both work on text. That is tempting, because the two names sound like a matched pair. Butsplit()goes from one string to a list of strings, andjoin()goes from a list of strings back to one string. The cure: say the direction out loud, "split makes a list, join makes a string," and check withtype()when you are unsure.
In practice (your tools). Paste the rebuild program into Python Tutor at pythontutor.com and step through it. After parts = entry.split(), a list of four strings appears beside entry. After the third line, position 2 of the list holds '30', while entry still holds the old line.
Memory hook: split takes the text apart; join puts it together again.
4. Know what split cuts on: whitespace versus a separator you choose
A paper cutter cuts where you line up the blade, and nowhere else. If you line it up on the spaces, a comma does not stop it. If you line it up on the commas, the spaces go straight through.
Worked example — the pinned split on whitespace. Predict how many items the list holds.
print("a,b c".split())
Output
['a,b', 'c']
There is one space in "a,b c", so split() with no argument cut once and handed back two items. The comma is an ordinary character to it, so 'a,b' stayed in one piece.
Worked example — hand it the comma. Give split() the separator you want.
print("a,b c".split(","))
Output
['a', 'b c']
Now the blade lines up on the comma. The string is cut once, at the comma, and the space between b and c stays inside the second item.
The same separator idea runs the other way in join(). The pinned "-".join(["a", "b", "c"]) prints a-b-c: one string, with a hyphen between each pair and none at the ends. A space as the separator, " ", rebuilt the reading-log line in Section 3.
Misconception check. Students often think
.split()with no argument splits on commas, because commas separate items in a list. That is tempting, because a comma-separated line looks like a list already. Butsplit()with nothing in its parentheses cuts only on whitespace. The cure: when the pieces are separated by commas, write the comma,split(","), and predict the list before you run it.
In practice (your tools). In your browser runner, type print("red, green, blue".split(",")) and predict it first. Look closely at the spaces left at the front of the second and third items; Section 7 shows how strip() removes them.
Memory hook: split cuts where you point it, not anywhere else.
5. Search with find: a position or minus one, never True or False
A library catalogue answers "where is this book?" with a shelf number. If the book is missing, it does not say "no"; it shows a code that means "not on the shelves." You have to know that code, or you will go looking for a shelf that does not exist.
.find() is the string method that hands back the position of the first match of the text it is given, counting from 0, or -1 when there is no match; it never hands back True or False.
Worked example — three searches. Predict all three lines.
s = "Hello, World"
print(s.find("Hello"))
print("z" in s)
print("World" in s)
Output
0
False
True
Hello starts at the very first position, so find handed back 0. The pinned method set in Section 1 already showed s.find("W") as 7 and s.find("z") as -1. The in test, which you used with lists in Week 9, also works on strings: it asks whether the text on the left appears anywhere inside the string on the right, and it does hand back True or False.
Worked example — the find bug. This program wants to report whether the string holds a z. Predict its one line.
s = "Hello, World"
if s.find("z"):
print("found a z")
else:
print("no z")
Output
found a z
There is no z in Hello, World, yet the program said it found one. Here is why. s.find("z") handed back -1. The if line then asked whether -1 is truthy, the Week 4 idea of a value that counts as true. Only the number 0 counts as false, so -1 counts as true and the if branch ran. The program raised no error, so this is a logic error.
Worked example — the fix. Compare with -1 instead.
s = "Hello, World"
if s.find("z") != -1:
print("found a z")
else:
print("no z")
Output
no z
Now the test asks the right question: "is the position anything other than -1?" The other cure is the in test, if "z" in s:, which hands back a real Boolean. The bug can bite the other way, too: a match at position 0, like Hello, hands back 0, which counts as false, so if s.find("Hello"): would skip a match that is really there.
Misconception check. Students often think
.find()returnsTrueorFalse, because the question "is it there?" sounds like a yes-or-no question. That is tempting, becausestartswith()andindo answer yes or no. Butfind()answers "where?", and its "nowhere" answer is the number-1. The cure: compare afindresult with!= -1, or useinwhen you only need yes or no.
In practice (your tools). Type the find bug into your browser runner and run it. Then change the condition to if "z" in s: and run it again. The Standard Library reference's String Methods section on docs.python.org states that find returns -1 when the text is not found.
Memory hook: find answers where, not whether; minus one means nowhere.
6. Replace and count every match at once
Anyone who has used find-and-replace in a word processor has seen it change every match in the document at once, not only the first. String methods behave the same way.
.replace() is the string method that takes an old piece of text and a new one and hands back a new string with every match of the old text swapped for the new one.
.count() is the string method that hands back how many times the text it is given appears in the string, counting matches that do not overlap.
Worked example — the to-do note. This illustrative to-do note says "buy" three times. Predict all three lines.
note = "buy milk, buy eggs, buy bread"
print(note.count("buy"))
print(note.replace("buy", "get"))
print(note)
Output
3
get milk, get eggs, get bread
buy milk, buy eggs, buy bread
count("buy") found 3 matches. replace("buy", "get") swapped all three in the new string it handed back, so buy appears nowhere in the second line. The third line shows the note itself, unchanged, because replace built a new string and the program printed it without storing it.
The pinned method set from Section 1 shows the same rule with single characters: s.replace("o", "0") printed Hell0, W0rld, with both o's changed, the one in Hello and the one in World.
Misconception check. Students often think
.replace()changes only the first match, because a person fixing a typo usually fixes one spot at a time. That is tempting, because the method's name sounds like a single action. Butreplace()swaps every match in the string. The cure: count the matches first withcount(), and expect that many changes.
In practice (your tools). In your browser runner, change the to-do program so that the note itself becomes the new version, with note = note.replace("buy", "get"), and predict the last line before you run it. That is the forgot-to-reassign cure from Section 2 again.
Memory hook: replace changes every match — but only in the copy.
7. Build small text algorithms from the pieces
A chef with a knife, a peeler, and a pan can make many dishes. You now have nine string methods, slices, and the for loop and counting idiom from earlier weeks. Put them together and you get the small text algorithms programs use every day.
Worked example — count the words. An illustrative group-chat message is split into words. Predict both lines.
msg = "meet me at the bike rack at noon"
words = msg.split()
print(len(words))
print(msg.count("at"))
Output
8
2
split() handed back a list of 8 words, and len() counted them. count("at") found the letters at twice. Here both matches are the word at, but count matches text anywhere, so it would also count the at inside a word such as chat. To count the words of any text, split it and count the list.
Normalize means to put text into one standard form before comparing it, such as trimming the spaces at both ends and turning every letter small, so that a reply typed as Yes matches yes.
.strip() is the string method that hands back a new string with the whitespace removed from both ends, while any spaces between words stay in place.
Worked example — normalize a reply. An illustrative event sign-up form gets the reply " Yes ", with two spaces before it and one after. Predict all three lines.
typed = " Yes "
print(typed == "yes")
clean = typed.strip().lower()
print(clean)
print(clean == "yes")
Output
False
yes
True
The first comparison is False, because the typed reply has spaces and a capital Y. typed.strip() hands back "Yes", and .lower() is called on that new string and hands back "yes". The two calls chain from left to right. After that, the comparison is True. This is how the club-fair sheet from the start of the chapter would count all its yeses.
Worked example — reverse a string. The pinned reverse uses the step slice you met in Week 3.
print("hello"[::-1])
Output
olleh
The slice [::-1] has no start, no stop, and a step of minus 1, so it walks the string from the last character to the first. No loop is needed. A word game uses the same slice to test whether a word reads the same both ways.
word = "level"
print(word[::-1])
print(word == word[::-1])
book = "river"
print(book[::-1])
Output
level
True
revir
level reversed is still level, so the comparison is True. river, the word in your reading log's book title, reversed is revir, a different string.
.startswith() is the string method that hands back True when the string begins with the text it is given and False when it does not.
Worked example — count the day lines. A reading log sometimes holds notes as well as days. This loop counts only the lines that start with "day".
lines = ["day 1: 12 pages", "note: library closed", "day 2: 40 pages"]
count = 0
for line in lines:
if line.startswith("day"):
count += 1
print(count)
Output
2
The counter starts at 0 before the loop, the way Week 5 set up every counter. The first line starts with day, so the count becomes 1; the note does not, so it is skipped; the third line starts with day, and 1 + 1 = 2.
Worked example — tally the words. Week 10's counting idiom works on any list, including the list split() hands back.
text = "red blue red red blue"
counts = {}
for w in text.split():
counts[w] = counts.get(w, 0) + 1
print(counts)
Output
{'red': 3, 'blue': 2}
split() turned one string into five words, and the idiom added one to each word's running total: 3 + 2 = 5 words in all. This is the same tally Week 10 pinned, now fed from a line of text.
Misconception check. Students often think you need a loop to reverse a string, because reversing sounds like stepping through it one character at a time. That is tempting, because a loop would work. But the slice
[::-1]already steps backward, in one expression. The cure: reach for the slice first, and save loops for jobs a single method or slice cannot do.
In practice (your tools). In your browser runner, change the group-chat message to one of your own and predict the word count before you run it. Then try the normalize program with a reply such as "YES" and predict the last line.
Memory hook: split to count; strip and lower to compare; step back to reverse.
8. Check a chatbot's claim with a run
A friend tells you a store's sign says it opens at nine. You can trust the friend, or you can walk past and read the sign. A chatbot's explanation of code is like the friend's report, and the run is the sign itself.
Worked example — a chatbot's claim about upper. Suppose you ask a chatbot what this program prints, and it answers: "upper() converts s to capitals, so the program prints HELLO." Run the pinned program and compare.
s = "Hello"
s.upper()
print(s)
Output
Hello
The run printed Hello. The chatbot described the method as if it changed the string in place, which is the exact slip from Section 2. Its claim becomes true only with the cure, s = s.upper(), which prints HELLO.
In words: the chatbot's sentence sounded reasonable and matched what the method is for, but it contradicted what the code prints. Your run settled it.
Misconception check. Students often think a chatbot's explanation must be right when it uses the right method name, because it plainly knows what
upperdoes. That is tempting, because the description ofupperwas accurate. But the question was what this program prints, and the chatbot never ran it. The cure: predict, then run, and compare every line of output with the claim.
In practice (your tools). Ask your approved chatbot to write a short program that counts the words in a sentence of your choice and to tell you the count. Before you run its code, count the words yourself. Then run it in your browser runner and compare the three numbers: yours, the chatbot's, and the run's. The Standard Library reference's String Methods section on docs.python.org is where to confirm how split() behaves.
Caveat: this chapter covers only the text tools Week 11 needs. Reading and writing files comes later, and so does handling a line that will not convert. Regular expressions, a more powerful pattern language for text, belong to a later course.
Pause and choose one of these to think about before you read on:
- (a) Think of text you deal with often, such as a shopping list, a playlist name, or a class schedule. Which string method would you use first to clean it up or take it apart, and what would you predict it hands back?
- (b) Think of a time a computer refused to match two things that looked the same to you, such as a username or a search. Which difference, a capital letter, a space, or something else, was most likely to blame, and which method would fix it?
Memory hook: trust the run, not the explanation.
Key terms
- string method — A function that belongs to a string and is called with a dot after it, such as upper in s.upper(); it hands back a new value and never changes the string itself. (first used: 1. Ask a string to do work: methods hand back new values)
- .upper() — The string method that hands back a new string with every letter turned into a capital letter, leaving digits, spaces, and punctuation as they were. (first used: 1. Ask a string to do work: methods hand back new values)
- .lower() — The string method that hands back a new string with every letter turned into a small letter, leaving digits, spaces, and punctuation as they were. (first used: 1. Ask a string to do work: methods hand back new values)
- forgot-to-reassign bug — The logic error of calling a string method on a line of its own and expecting the string to change; the new string is lost unless it is assigned back to the name. (first used: 2. Keep the new value: the forgot-to-reassign bug)
- whitespace — The characters that show up as blank space when text is printed, such as an ordinary space, a tab, and the line break at the end of a line. (first used: 3. Take a line apart and rebuild it: split and join)
- .split() — The string method that cuts a string into pieces and hands back a list of strings; with empty parentheses it cuts on whitespace, and given a separator such as a comma it cuts there instead. (first used: 3. Take a line apart and rebuild it: split and join)
- separator — The piece of text that sits between the parts when strings are joined, or that a string is cut on when it is split, such as a space, a comma, or a hyphen. (first used: 3. Take a line apart and rebuild it: split and join)
- .join() — The string method called on a separator that hands back one new string made from a list of strings, with the separator placed between each neighbouring pair. (first used: 3. Take a line apart and rebuild it: split and join)
- .find() — The string method that hands back the position of the first match of the text it is given, counting from 0, or -1 when there is no match; it never hands back True or False. (first used: 5. Search with find: a position or minus one, never True or False)
- .replace() — The string method that takes an old piece of text and a new one and hands back a new string with every match of the old text swapped for the new one. (first used: 6. Replace and count every match at once)
- .count() — The string method that hands back how many times the text it is given appears in the string, counting matches that do not overlap. (first used: 6. Replace and count every match at once)
- normalize — To put text into one standard form before comparing it, such as trimming the spaces at both ends and turning every letter small, so that a reply typed as Yes matches yes. (first used: 7. Build small text algorithms from the pieces)
- .strip() — The string method that hands back a new string with the whitespace removed from both ends, while any spaces between words stay in place. (first used: 7. Build small text algorithms from the pieces)
- .startswith() — The string method that hands back True when the string begins with the text it is given and False when it does not. (first used: 7. Build small text algorithms from the pieces)
Summary
- A string method is called with a dot and hands back a new value.
- A string never changes; store the new value, as in
s = s.upper(). split()makes a list;join()makes a string.split()with no argument cuts on whitespace, not on commas.find()hands back a position or-1, neverTrueorFalse.- Test for a match with
!= -1or within. replace()andcount()work on every match.- Count words with
len(text.split()); normalize with.strip().lower(); reverse with[::-1].
Check your understanding
Work these before looking at the answers — they are ungraded, and the answers (with reasoning) are at the bottom of the page.
- A bike-share app in an illustrative example stores a dock label as
code = " dock-12 ". Predict whatprint(code.strip().upper())prints, and then whatprint(len(code.strip()))prints. - A baking app in an illustrative example stores
items = "flour,sugar,eggs". Predict whatprint(items.split(","))prints and whatprint(items.split())prints, and say why they differ. - A step counter in an illustrative example stores
report = "steps: 6400". Predict whatprint(report.find(":"))prints and whatprint(int(report.split()[1]) + 600)prints. - A password checker in an illustrative example stores
pw = "sunflower"and runsif pw.find("s"):withprint("has an s")in its block andprint("no s")underelse:. Predict the output, and say how to fix the test.
Answers (worked reasoning — read after attempting)
- The first line is DOCK-12.
strip()removes the two spaces at the front and the one at the end, handing back"dock-12", andupper()capitalizes the letters while the hyphen and digits stay as they were. The second line is 7, because"dock-12"has 4 letters, a hyphen, and 2 digits, and 4 + 1 + 2 = 7. - The first line is
['flour', 'sugar', 'eggs'], because the comma is the separator, so the string is cut at both commas into 3 items. The second line is['flour,sugar,eggs'], a list holding one item, becausesplit()with no argument cuts only on whitespace and this string has none. The commas only count when you hand them tosplit(). - The first line is 5, because counting from 0 the letters of
stepsfill positions 0 to 4 and the colon sits at position 5. The second line is 7000:report.split()hands back['steps:', '6400'], position 1 is the string'6400',int()turns it into the number 6400, and 6400 + 600 = 7000. - The program prints no s, even though
sunflowerstarts with an s.pw.find("s")hands back 0, the position of the first letter, and 0 counts as false, so theelsebranch runs. This is the find bug from Section 5, the other way round. Fix it withif "s" in pw:orif pw.find("s") != -1:, and the program prints has an s.
Next up in this module: the Readings & Resources page, the lecture tutorial, the practice set, and the quiz — and next week, the with statement reads files line by line, so this split-and-strip rule meets every line.
Built with The Course Maker · samples.thecoursemaker.com