Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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.

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.

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.

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 that s[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.

Exercise L6.2 (LO-6.1, ★★, about 10 minutes)

Write two functions with indexing and slicing:

  1. capitalize_first(word) returns word with its first character in capitals and the rest unchanged: capitalize_first("python") is "Python". It must work for the empty string too, and return "".

  2. last_n(text, n) returns the last n characters of text, or the whole of text if it has fewer than n: last_n("spreadsheet", 5) is "sheet", last_n("abc", 5) is "abc", and last_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.

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.

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")

Exercise L6.4 (LO-6.2, ★★, about 15 minutes)

Write three functions with string methods:

  1. username(full_name) returns the words of a name in lowercase, joined by dots, ignoring extra spaces: username(" Ada Lovelace ") is "ada.lovelace".

  2. 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".

  3. is_palindrome(text) returns True if the text reads the same backward, ignoring spaces and case: is_palindrome("Never odd or even") is True.

Hint

username needs three methods. In email_domain, think about what find returns when there is no @, and what slice that gives.

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.

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.

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.

  1. clean_word(word) strips the characters in PUNCTUATION from both ends of word and returns it in lowercase: clean_word('"Far') is "far", and clean_word("--") is "". An apostrophe or hyphen inside a word stays.

  2. word_count(text) returns how many words text has.

  3. count_word(text, target) returns how many of the words, once cleaned, are target, ignoring case: count_word(PASSAGE, "Rules") is 3.

  4. longest_word(text) returns the longest cleaned word, and the first one if several are equally long.

  5. 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.

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.

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".

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:

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.

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.

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"

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 ord and chr, and broke a message by trying every shift; and

  • saw that len counts code points, which can differ from bytes and from what a reader sees.

Next, the Module 6 practice gives you more exercises with answers.