Chapter 3 · Data
Working with text
Step 1 of 22 · Concept
Each character has a number
In this lesson you take text apart, make new text from it, and line it up in columns.
word = "Python"
- Each character has a number, its index. The first is 0.
word[0]is"P". Counting from the end, the last is -1:word[-1]is"n".
Step 2 of 22 · Quiz
Predict the characters
Type exactly what this program prints.
word = "Python"
print(word[1], word[-1])
Step 3 of 22 · Demo
See it run
Run it and compare with your answer. Then print word[2] and word[-3] too.
Step 4 of 22 · Demo
One too far
word has 6 characters, so its indices go from 0 to 5. Run it: index 6 is past the end. Read the traceback's
last line first (lesson 5).
Step 5 of 22 · Concept
A slice takes a piece
A slice takes a piece of the text: word[start:stop]. It stops before stop.
| slice | gives |
|---|---|
word[1:4] | "yth": indices 1, 2 and 3 |
word[:3] | "Pyt": from the start |
word[3:] | "hon": to the end |
word[::-1] | "nohtyP": backwards |
A third number is the step: -1 walks backwards. A slice past the end stops there: word[3:100] is "hon".
Step 6 of 22 · Demo
Five slices
Run it. The last slice asks for more characters than there are, and gets what there is, with no error.
Step 7 of 22 · Exercise
Your turn: initials
Use indices in f-strings (lesson 4).
- Print the initials of
firstandlast, each with a dot. - Print the first name, a space and the last name's initial with a dot.
The program must print:
A.L.
Ada L.
The first letter of first is first[0], and of last, last[0].
In an f-string, {first[0]} puts that letter into the text. The dots are plain text around it.
print(f"{first[0]}.{last[0]}.")
Step 8 of 22 · Concept
Text never changes
Text cannot change. word[0] = "J" stops with TypeError: 'str' object does not support item assignment.
word = "ada"
word.upper()
word = word.upper()
upper()is a method: a function that belongs to a value, called after a dot.- Line 2 makes a new text,
"ADA", and no name keeps it. - Line 3 gives the new text the name
word: the arrow moves.
Step 9 of 22 · Try it
Try it: a capital J
Run it: TypeError: 'str' object does not support item assignment. Text cannot change, so make a new one.
Replace line 2 with word = "J" + word[1:]. Then it prints Java.
word[1:] is every character but the first, "ava". + joins two texts into a new one (lesson 4).
Step 10 of 22 · Concept
What text can do
Each method returns a new value. The text it is called on stays as it was.
| call | gives |
|---|---|
"Ada".upper() | "ADA" |
"Ada".lower() | "ada" |
" Ada ".strip() | "Ada": no spaces, tabs or new lines at either end |
"a-b".replace("-", "+") | "a+b": every - replaced |
"banana".find("n") | 2, the first index of "n"; -1 if absent |
"Ada".startswith("A") | True |
Two more: "banana".count("a") is 3. "42".isdigit() is True: the text is only digits.
In text, "\n" is a new line and "\t" a tab. Methods can follow each other: text.strip().upper() calls
upper on the text strip made.
Step 11 of 22 · Quiz
Predict the clean-up
Type exactly what this program prints.
name = " Ada Lovelace\n"
clean = name.strip()
print(clean.upper())
print(clean.lower().replace(" ", "."))
print(clean.find("L"), clean.count("a"))
print(clean.startswith("Ada"), "42".isdigit())
Step 12 of 22 · Demo
See it run
Run it and compare with your answer. Then add print(name): the space and the new line are still there, since
strip() made a new text.
Step 13 of 22 · Demo
split cuts, join glues
| call | gives |
|---|---|
"a b c".split() | a list of the words: ['a', 'b', 'c'] |
"-".join(words) | the words joined, with - between them |
A list holds several values in order; lesson 10 is about lists.
Run it. print shows each "\n" as a new line, and split("\n") cuts the text there.
Step 14 of 22 · Demo
for walks through text
for ch in word: runs its block once for each character. for also walks through the words that split()
gives.
"a" in word asks whether "a" appears in word. Run it.
Step 15 of 22 · Exercise
Your turn: an acronym
Finish acronym(text): it returns the first letter of each word, in capitals. The program must print:
PNG
CPU
Start from empty text, then add one letter for each word of text.split().
Loop with for w in text.split():. Inside, add w[0] in capitals to the text with +=. Return it after the loop.
letters += w[0].upper()
Step 16 of 22 · Concept
Format specs line up columns
After the value and a colon in an f-string, a format spec says how to show the value.
| spec | shows the value |
|---|---|
{name:<8} | at the left of 8 columns |
{qty:>4} | at the right of 4 columns |
{title:^12} | in the middle of 12 columns |
{price:.2f} | with 2 decimals (lesson 4) |
{big:,} | with commas: 1,500,000 |
Spaces fill the free columns, so rows line up.
Step 17 of 22 · Quiz
Predict the table
The square brackets show where each line starts and ends. Type exactly what this program prints.
title = "Menu"
item = "tea"
qty = 3
big = 1500000
print(f"[{title:^12}]")
print(f"[{item:<8}{qty:>4}]")
print(f"{big:,} cups")
Step 18 of 22 · Demo
See it run
Run it and compare with your answer. Then change <8 to >8 and run it again.
Step 19 of 22 · Demo
== compares text
== compares text character by character, and capitals count, so compare .lower() text.
is asks something else: "the same object?" Equal text can be two objects, so never use is on text. Run it.
Step 20 of 22 · Check yourself
Check yourself: a username
- Read a full name with
input("Name: "). - Make the username: no spaces at either end, lower case, each space a
., at most 8 characters. - Print
User:and the username, then the username in the middle of 20 columns, in square brackets.
The name typed is Grace Hopper, with a space before and after. The output must be exactly:
Name: User: grace.ho
[ grace.ho ]
Each part is one method or one slice, applied to the text the part before made.
Step 21 of 22 · Challenge · optional
Challenge: a secret shift
Optional.
Shift each letter of "python" 3 places on in the alphabet. After z comes a again, so y becomes b. The
program must print:
sbwkrq
Every character has a number: ord("a") is 97, ord("b") 98. chr(98) turns the number back into "b".
ord(ch) - ord("a") gives 0 for a, up to 25 for z. Add 3, then % 26 wraps 26 back to 0 (lesson 3).
n = (ord(ch) - ord("a") + 3) % 26
Step 22 of 22 · Recap
Recap
word[0]is the first character,word[-1]the last; past the end is anIndexError.word[1:4]stops before index 4;word[::-1]is the text backwards.- Text never changes: a method such as
upper()makes a new text. split()cuts text into words,"-".join(words)glues them back.{name:<8},{qty:>4}and{title:^12}line values up in columns.
Next: lesson 10 keeps many values in one list, and a list can change.
Review
3 questions from this lesson, in a new order each time. Answer from memory: 2 of 3 right on the first try passes. On a day after you finish the lesson, a pass earns 15 XP.
The review needs JavaScript.
word = "Python"
print(word[1], word[-1])
word = "Python"
print(len(word))
print(word[6])
word = "Python"
print(word[1:4])
print(word[:3])
print(word[3:])
print(word[::-1])
print(word[3:100])
first = "Ada"
last = "Lovelace"
# 1. print the initials: A.L.
# 2. print the first name and the last initial
word = "java"
word[0] = "J"
print(word)
name = " Ada Lovelace\n"
clean = name.strip()
print(clean.upper())
print(clean.lower().replace(" ", "."))
print(clean.find("L"), clean.count("a"))
print(clean.startswith("Ada"), "42".isdigit())
sentence = "the quick brown fox"
words = sentence.split()
print(words)
print("-".join(words))
print(len(words), "words")
lines = "one\ntwo"
print(lines)
print(lines.split("\n"))
print("Ada\t36")
word = "cat"
for ch in word:
print(ch)
for w in "big red dog".split():
print(w, len(w))
print("a" in word, "dog" in word)
def acronym(text):
# the first letter of each word, in capitals
return ""
print(acronym("portable network graphics"))
print(acronym("central processing unit"))
title = "Menu"
item = "tea"
qty = 3
big = 1500000
print(f"[{title:^12}]")
print(f"[{item:<8}{qty:>4}]")
print(f"{big:,} cups")
name = "Ada"
typed = "ada"
print(name == typed)
print(name.lower() == typed.lower())
fixed = typed[0].upper() + typed[1:]
print(fixed == name, fixed is name)
# read the name, make the username,
# then print the two lines
word = "python"
secret = ""
# shift each letter 3 places on
print(secret)