Objectives: LO-6.1, LO-6.2, LO-6.3, LO-6.4
Prerequisites: the Module 6 reading and Lab 5
Time: about 2 hours
In this lab you index and slice strings, predict what string methods return, write functions
that clean and check text, count the words of a passage, build a Caesar cipher and break a
message written with it, and look at the code points behind accented letters and emoji. As
before, each exercise ends with a check cell that prints passed or says what is wrong, and
fails until you answer.
Setup¶
Run the next cell first. It prints the version of Python and imports two modules: math, for
math.isclose, and unicodedata, the standard library’s facts about Unicode characters, which
the last section uses.
import math
import sys
import unicodedata
print("Python", sys.version.split()[0])1. Indexing and slicing¶
Run the next cell, then change text and the numbers in it, and run it again. Try an index past
the end, a negative step, and a slice whose start is after its stop.
text = "spreadsheet"
print(len(text))
print(text[0], text[-1], text[3])
print(text[2:6], text[:6], text[6:])
print(text[::2], text[::-1])Strings can’t be changed. Delete the # at the start of the second line of the next cell, run
the cell, and read the error. Then put the # back. The third line shows what works instead:
building a new string.
word = "Python"
# word[0] = "J"
word = "J" + word[1:]
print(word)Exercise L6.1 (LO-6.1, ★, about 10 minutes)¶
With s = "spreadsheet", predict each value without running anything. Write each one as a
string, such as "x", or "" for the empty string.
p1:s[1]p2:s[-2]p3:s[2:6]p4:s[6:]p5:s[-5:-2]p6:s[::3]p7:s[8:3:-1]p8:s[20:]p9: the kind of error thats[11]raises, such as"TypeError"
Then check your predictions in a cell of your own. Writing out the indices under the letters, as the reading’s table does, helps.
p1 = "..."
p2 = "..."
p3 = "..."
p4 = "..."
p5 = "..."
p6 = "..."
p7 = "..."
p8 = "..."
p9 = "..."s = "spreadsheet"
assert p1 == s[1], "p1: the first character is at index 0."
assert p2 == s[-2], "p2: -1 is the last character."
assert p3 == s[2:6], "p3: a slice stops just before its stop index."
assert p4 == s[6:], "p4: a slice with no stop runs to the end."
assert p5 == s[-5:-2], "p5: count -5 and -2 from the end; -2 itself is left out."
assert p6 == s[::3], "p6: every third character, starting at index 0."
assert p7 == s[8:3:-1], "p7: a negative step goes backward, stopping just before index 3."
assert p8 == s[20:], "p8: a slice past the end is never an error."
assert p9 == "IndexError", "p9: what happens to an index past the end of a string?"
print("passed")Exercise L6.2 (LO-6.1, ★★, about 10 minutes)¶
Write two functions with indexing and slicing:
capitalize_first(word)returnswordwith its first character in capitals and the rest unchanged:capitalize_first("python")is"Python". It must work for the empty string too, and return"".last_n(text, n)returns the lastncharacters oftext, or the whole oftextif it has fewer thann:last_n("spreadsheet", 5)is"sheet",last_n("abc", 5)is"abc", andlast_n("abc", 0)is"".
Hint 1
word[0] is an IndexError for the empty string, but a slice never is: what is word[:1]?
Hint 2
Try text[-n:] with n set to 0, and work out why it gives the whole string. Counting the start from the left, as len(text) - n, avoids that, but then check what happens when n is more than the length.
def capitalize_first(word):
"""Return word with its first character in capitals."""
...
def last_n(text, n):
"""Return the last n characters of text, or all of text if it is shorter."""
...assert capitalize_first("python") == "Python", "capitalize_first('python') should be 'Python'."
assert capitalize_first("iPhone") == "IPhone", "Change only the first character."
assert capitalize_first("x") == "X", "A one-character word should work too."
assert capitalize_first("") == "", "The empty string should give the empty string, not an error."
assert last_n("spreadsheet", 5) == "sheet", "last_n('spreadsheet', 5) should be 'sheet'."
assert last_n("abc", 3) == "abc", "Asking for exactly all the characters gives them all."
assert last_n("abc", 5) == "abc", "Asking for more characters than there are gives them all."
assert last_n("abc", 0) == "", "Asking for 0 characters gives the empty string."
print("passed")2. String methods¶
Run the next cell, and then try other methods and arguments on messy. Remember that a method
returns a new string: messy itself never changes.
messy = " Hello, World! "
print(repr(messy.strip()))
print(repr(messy.lower()))
print(repr(messy.replace("l", "L")))
print(messy.find("World"), messy.count("l"), "World" in messy)
print(messy.split())
print(repr(messy))Exercise L6.3 (LO-6.2, ★, about 10 minutes)¶
Predict each value, then check your predictions in a cell of your own. Write strings in quotes,
and numbers and True or False without them.
m1:"Mississippi".find("ss")m2:"Mississippi".count("ss")m3:"Mississippi".find("x")m4:"Mississippi".replace("ss", "s")m5:"Mississippi".strip("Mi")m6:len(" to do ".strip())m7:len("to,do,,list".split(","))m8:"/".join("abc")m9:"Data.CSV".lower().endswith(".csv")
m1 = ...
m2 = ...
m3 = ...
m4 = "..."
m5 = "..."
m6 = ...
m7 = ...
m8 = "..."
m9 = ...river = "Mississippi"
assert m1 == river.find("ss"), "m1: find gives the index of the first match."
assert m2 == river.count("ss"), "m2: count the matches; they don't overlap here."
assert m3 == river.find("x"), "m3: what does find return when there is no match?"
assert m4 == river.replace("ss", "s"), "m4: replace changes every match, not only the first."
assert m5 == river.strip("Mi"), "m5: strip removes any of the given characters, from both ends."
assert m6 == len(" to do ".strip()), "m6: strip leaves the space between the words."
assert m7 == len("to,do,,list".split(",")), "m7: two commas side by side leave an empty piece."
assert m8 == "/".join("abc"), "m8: join treats a string as its characters."
assert m9 == "Data.CSV".lower().endswith(".csv"), "m9: lower runs first, then endswith."
print("passed")Exercise L6.4 (LO-6.2, ★★, about 15 minutes)¶
Write three functions with string methods:
username(full_name)returns the words of a name in lowercase, joined by dots, ignoring extra spaces:username(" Ada Lovelace ")is"ada.lovelace".email_domain(address)returns the part of an email address after the first@, or""if it has no@:email_domain("[email protected]")is"example.com".is_palindrome(text)returnsTrueif the text reads the same backward, ignoring spaces and case:is_palindrome("Never odd or even")isTrue.
Hint
username needs three methods. In email_domain, think about what find returns when there is no @, and what slice that gives.
def username(full_name):
"""Return the words of full_name in lowercase, joined by dots."""
...
def email_domain(address):
"""Return the part of address after its first @, or "" if it has none."""
...
def is_palindrome(text):
"""Return True if text reads the same backward, ignoring spaces and case."""
...assert username(" Ada Lovelace ") == "ada.lovelace", "Lowercase, drop extra spaces, join by dots."
assert username("Grace Brewster Hopper") == "grace.brewster.hopper", "Join every word."
assert username("Ada") == "ada", "A one-word name has no dots."
assert email_domain("[email protected]") == "example.com", "Take everything after the @."
assert email_domain("a@b@c") == "b@c", "Split at the first @."
assert email_domain("no-at-sign") == "", (
f"email_domain('no-at-sign') gave {email_domain('no-at-sign')!r}: check for a missing @."
)
assert is_palindrome("Never odd or even"), "Ignore the spaces and the capital N."
assert is_palindrome("level") and is_palindrome(""), "level and the empty string are palindromes."
assert not is_palindrome("Python"), "Python isn't a palindrome."
print("passed")3. Processing text one character at a time¶
Exercise L6.5 (LO-6.3, ★★, about 10 minutes)¶
Web pages write colors as a # followed by six hexadecimal digits, each one of 0 to 9,
a to f, or A to F: "#1A2b3C". Write is_hex_color(text), which returns True only for
text of exactly that form.
Hint
Check the length and the # first, then loop over text[1:] and return False at the first character that isn’t in "0123456789abcdefABCDEF", as the reading’s is_product_code does.
def is_hex_color(text):
"""Return True if text is # followed by six hexadecimal digits."""
...assert is_hex_color("#1A2b3C") is True, "#1A2b3C is a color: return True."
assert is_hex_color("#000000") is True, "#000000 (black) is a color."
assert is_hex_color("1A2b3C") is False, "Without the # it isn't one."
assert is_hex_color("#1A2b3") is False, "Five digits are too few."
assert is_hex_color("#1A2b3C4") is False, "Seven digits are too many."
assert is_hex_color("#1A2g3C") is False, "g isn't a hexadecimal digit."
assert is_hex_color("#1A 23C") is False, "A space isn't a hexadecimal digit."
assert is_hex_color("") is False, "The empty string isn't a color, and mustn't be an error."
assert is_hex_color("#123456") is False, "Full-width digits pass isdigit, but aren't 0 to 9."
print("passed")4. Processing text one word at a time¶
Here is a passage written for this course. It has what real text has: capitals, punctuation stuck to words, a dash on its own, quotation marks, an apostrophe inside a word, extra spaces, and line breaks. Run the cell to store it.
PASSAGE = """The Riverside Community Garden opened in the spring of 2019. That first year,
twelve families shared the plots; by 2026 there were forty-one. Each plot is three
meters by four -- enough for tomatoes, beans, and "far too many" zucchini.
The garden's rules are short: water in the morning, share the tools, and don't
leave the gate open. Other gardens have longer rules. This one, the volunteers say,
works because the rules fit on a single sign."""
PUNCTUATION = '.,;:!?"()-'Exercise L6.6 (LO-6.3, ★★, about 25 minutes)¶
Write five functions. A word is anything split() gives that isn’t empty once it has been
cleaned, so "--" isn’t a word, but "2019." and "forty-one." are.
clean_word(word)strips the characters inPUNCTUATIONfrom both ends ofwordand returns it in lowercase:clean_word('"Far')is"far", andclean_word("--")is"". An apostrophe or hyphen inside a word stays.word_count(text)returns how many wordstexthas.count_word(text, target)returns how many of the words, once cleaned, aretarget, ignoring case:count_word(PASSAGE, "Rules")is 3.longest_word(text)returns the longest cleaned word, and the first one if several are equally long.average_word_length(text)returns the average number of characters in the cleaned words.
Use clean_word in the other four. After the check passes, compare your count_word(PASSAGE, "the") with PASSAGE.lower().count("the"), and work out why they differ.
def clean_word(word):
"""Return word in lowercase, without PUNCTUATION at either end."""
...assert clean_word("Garden's") == "garden's", "Keep the apostrophe inside a word."
assert clean_word('"far') == "far", "Strip the quotation mark."
assert clean_word("forty-one.") == "forty-one", "Strip the period, keep the hyphen inside."
assert clean_word("--") == "", "A dash on its own cleans to the empty string."
assert word_count("one two three") == 3, "Extra spaces don't make extra words."
assert word_count("wait -- what?") == 2, "-- isn't a word."
assert word_count(PASSAGE) == 76, f"PASSAGE has 76 words, not {word_count(PASSAGE)}."
assert count_word(PASSAGE, "rules") == 3, "rules appears three times."
assert count_word(PASSAGE, "Garden") == 1, "Ignore the case of target; garden's is another word."
assert count_word(PASSAGE, "the") == 9, (
f"the is a word 9 times in PASSAGE, not {count_word(PASSAGE, 'the')}: compare whole words."
)
assert longest_word("Ab, cd! ef") == "ab", "Return the first of equally long words."
assert longest_word(PASSAGE) == "volunteers", "Clean each word before you measure it."
assert math.isclose(average_word_length("Hi, there!"), 3.5), "Hi and there average 3.5 letters."
assert math.isclose(average_word_length("a -- bcd"), 2), "Don't count -- as a word."
print("passed")Once the check passes, run the next cell for a summary of the passage. Then put a paragraph of
your own into PASSAGE, and run both cells again.
print(word_count(PASSAGE), "words")
print("the:", count_word(PASSAGE, "the"), "as a word,", PASSAGE.lower().count("the"), "with count")
print("longest:", longest_word(PASSAGE))
print(f"average length: {average_word_length(PASSAGE):.2f}")5. Characters and code points¶
Exercise L6.7 (LO-6.4, ★★, about 15 minutes)¶
Write caesar(text, shift), which returns text with every letter from a to z and from
A to Z moved shift places along the alphabet, wrapping around, and keeping its case. Every
other character, such as a space, a digit, punctuation, or é, stays as it is.
caesar("Hello, World!", 3) is "Khoor, Zruog!", and a negative shift moves letters back, so
caesar(caesar(message, 3), -3) is message again.
Hint 1
Start from the reading’s shift_letter, which shifts a lowercase letter. Capitals work the same way, counting from ord("A") instead of ord("a").
Hint 2
"é".isalpha() and "é".islower() are both True, so neither tells you that a character is between a and z. A chained comparison does: "a" <= character <= "z".
def caesar(text, shift):
"""Return text with each letter a-z and A-Z moved shift places along the alphabet."""
...assert caesar("abc", 1) == "bcd", "Each letter moves one place: abc becomes bcd."
assert caesar("xyz", 3) == "abc", "Wrap around after z."
assert caesar("Hello, World!", 3) == "Khoor, Zruog!", "Keep capitals, spaces, and punctuation."
assert caesar("Zz", 1) == "Aa", "Capitals wrap from Z to A."
assert caesar("def", -3) == "abc", "A negative shift moves letters back."
assert caesar("abc", 29) == "def", "A shift of 29 is the same as a shift of 3."
assert caesar("café 2026", 1) == "dbgé 2026", "Leave é and digits as they are."
message = "The quick brown fox jumps over the lazy dog."
assert caesar(caesar(message, 7), -7) == message, "Shifting back should give the message again."
print("passed")Exercise L6.8 (LO-6.3, LO-6.4, ★★, about 10 minutes)¶
Someone wrote this message with a Caesar cipher, and didn’t say the shift:
SECRET = "Xppe esp gzwfyeppcd le esp rlcopy rlep le dpgpy, lyo mctyr esp dalcp vpj."Write a loop that tries every shift from 1 to 25, and find the one that turns SECRET back into
English. Set secret_shift to the shift that was used to make SECRET, and plain to the
message. Print each try first, and read them; then make the loop find the shift by itself, for
example by looking for " the " in each try.
secret_shift = ...
plain = "..."assert secret_shift in range(1, 26), "The shift is from 1 to 25."
assert caesar(plain, secret_shift) == SECRET, (
"Shifting plain by secret_shift should give SECRET. Did you give the shift that undoes it?"
)
assert " the " in plain, "plain should be the English message."
print("passed")Code points beyond ASCII¶
The next cell defines a function that prints each code point of a string: its number in
hexadecimal, after U+, and its name in Unicode. :04X writes a number in hexadecimal, with
capital letters and at least four digits. Run it, then try other text: your name, a word in
another language, or emoji.
def show_code_points(text):
"""Print each code point of text, as U+ and its number in hexadecimal, and its name."""
for character in text:
print(f"U+{ord(character):04X} {unicodedata.name(character, '(no name)')}")
show_code_points("café")
print()
show_code_points("cafe\u0301")
print()
show_code_points("👋🏽")Exercise L6.9 (LO-6.4, ★, about 10 minutes)¶
"naïve" below is written with ï as one code point, and "nai\u0308ve" with an i
followed by U+0308, the combining diaeresis. Predict each value, then check your predictions in
a cell of your own:
q1:len("naïve")q2:len("nai\u0308ve")q3:len("naïve".encode("utf-8"))q4:len("🐍🐍".encode("utf-8"))q5:"nai\u0308ve" == "naïve"q6:unicodedata.normalize("NFC", "nai\u0308ve") == "naïve"
q1 = ...
q2 = ...
q3 = ...
q4 = ...
q5 = ...
q6 = ...assert q1 == len("naïve"), "q1: len counts code points, and ï is one here."
assert q2 == len("nai\u0308ve"), "q2: the i and its combining mark are two code points."
assert q3 == len("naïve".encode("utf-8")), "q3: UTF-8 stores ï in more than one byte."
assert q4 == len("🐍🐍".encode("utf-8")), "q4: UTF-8 uses up to 4 bytes per code point."
assert q5 == ("nai\u0308ve" == "naïve"), "q5: equal strings have the same code points."
assert q6 == (unicodedata.normalize("NFC", "nai\u0308ve") == "naïve"), (
"q6: NFC turns a letter and a combining mark into one code point where Unicode has one."
)
print("passed")A username limit of “10 characters”, checked with len, lets through 10 code points: perhaps
five emoji with skin tones, which a reader sees as five characters. Programs that limit or cut
text for people to read have to decide what a character means.
Summary¶
In this lab you:
predicted indices and slices, and wrote functions that use slices because a slice is never an error;
predicted what string methods return, and used them to build usernames, read email addresses, and test palindromes;
validated text one character at a time, and cleaned and counted the words of a passage;
built a Caesar cipher with
ordandchr, and broke a message by trying every shift; andsaw that
lencounts code points, which can differ from bytes and from what a reader sees.
Next, the Module 6 practice gives you more exercises with answers.