A brief note on Working with Text and Real Projects: split(), join() and strip(), cleaning and counting words, letter codes and f-strings, looking inside text, and a method for building your own projects. With a worked example, practice, a program and questions to check yourself.
A brief note on Working with Text and Real Projects. Read it before a test. Try each question at the end before you open its answer.
split() cuts a string into a list of words, at any run of spaces. split(",") cuts at each comma."-".join(words) glues a list of strings into one string. The separator comes first.strip() removes the spaces at the two ends. strip(".,!") removes those marks instead.replace(old, new) changes every match. startswith(), endswith() and in answer True or False.name = name.strip().lower(), then replace every punctuation mark by a space.split() gives the words, and a dictionary counts them: counts[w] = counts.get(w, 0) + 1.max(words, key=len) is the longest word. max(counts, key=counts.get) is the most common one.max meets. Decide on a tie rule, and write it down.ord("a") is 97, and chr(97) is "a".(place + shift) % 26. The % 26 wraps z round to a. To decode, use -shift.text[::-1]. Two anagrams give the same sorted() letters.e is the most common letter. That cracks a Caesar code.| Format | Shows | Example result |
|---|---|---|
f"{x:.2f}" | 2 decimal places | 3.14 |
f"{name:<8}" | left, in 8 places | Asha |
f"{n:>6}" | right, in 6 places | 42 |
f"{n:,}" | commas | 12,500 |
f"{part:.0%}" | a percentage | 75% |
find() gives a position, or -1. index() stops with an error instead. count() says how many.isdigit(), isalpha(), isalnum(), isspace(), isupper() and islower() test the kind of characters.partition("=") cuts at the first = into three parts. An empty middle part means the separator was missing.input() and print(), so that a table of tests can check them.lower().statistics.mean(), median() and stdev() summarise marks. An empty list raises a StatisticsError.EOFError, so that a program that reads input ends cleanly.Which word is the most common in " Rain, rain... go AWAY! Rain! "? Follow the cleaning one step at a time.
lower() gives " rain, rain... go away! rain! ".,, . and ! is replaced by a space. Only spaces and letters are left.split() cuts at every run of spaces: ['rain', 'rain', 'go', 'away', 'rain'].{'rain': 3, 'go': 1, 'away': 1}.max(counts, key=counts.get) gives 'rain'.Without step 1, Rain and rain would be two different words. Without step 2, rain, and rain would be two more.
A small text toolkit: it counts the words of a line, finds the longest and the most common, and codes a message.
name.strip() on its own changes nothing, because a string never changes. Write name = name.strip().split(" ") for words. Two spaces in a row make an empty word, ''. Use split().words.join("-") stops with AttributeError: 'list' object has no attribute 'join'. Write "-".join(words)."-".join([4, 5]) stops with TypeError: sequence item 0: expected str instance, int found. Change them to text first.index() for a missing piece. "cat".index("z") stops with ValueError: substring not found. find() gives -1 instead.% 26. The letter z moved by 2 becomes |, not b.contacts["Zara"] for a name that is not in the book stops with KeyError: 'Zara'. Ask with in first, or use get().{"add": do_add()} calls the function at once. Write do_add." apples, 40 kg ".strip().partition(",") give?"12.5".isdigit() False? How else could a program check that a text is a decimal number?h. Which shift was used? (e is at place 4, and h is at place 7.)Rs 1,234.50.input() and print()?Log in to join the discussion.
Loading…