Quick check
After these two lines, what does print(name) show?
name = "maya" then name.upper()
Show the answer
Answer: maya. The method built "MAYA" but the result was not stored. name = name.upper() would change what name refers to.
Ultimate Core Python · Chapter 9
This lesson goes with Episode 9 of the Ultimate Core Python course on the Core by Critic channel on YouTube.
A method is a function that belongs to a value. You call it by writing the value, a dot, the method's name and brackets:
word = "python"
print(word.upper())Output
PYTHON
Read word.upper() as "word, give me your uppercase version". Compare the two styles of call you now know:
function call method call
len(word) word.upper()
│ │ │ │
name value value name
With a function such as len, the value goes inside the brackets. With a method, the value goes in front of the dot. Why two styles? len works on many kinds of things (strings, and later lists and dictionaries), so it stands on its own. upper only makes sense for strings, so it lives inside the string type. The dot means "look inside this value for something named...".
Methods work on any string value, not just variables:
print("hello".upper())
print(("py" + "thon").upper())
print(str(3.5).replace(".", ","))Output
HELLO PYTHON 3,5
Like functions, many methods take arguments inside the brackets, as replace does above.
Strings are immutable (Chapters 7 and 8). So a string method can never change the string it is called on. It builds a new string and gives that back.
word = "python"
word.upper()
print(word)Output
python
The second line did make "PYTHON", but nobody caught it, so it was thrown away. word is exactly as before. This is the most common string bug there is. To keep the result, store it:
word = "python"
shout = word.upper()
print(word, shout)
word = word.upper() # or move the same label to the new string
print(word)Output
python PYTHON PYTHON
Without brackets you are not calling the method. You are just looking at it:
word = "python"
print(word.upper)Output
<built-in method upper of str object at 0x...>
That odd line is Python's way of saying "this is the upper method of a string that lives at this memory address". No error, and no uppercase either. The brackets are what make it run.
Quick check
After these two lines, what does print(name) show?
name = "maya" then name.upper()
Answer: maya. The method built "MAYA" but the result was not stored. name = name.upper() would change what name refers to.
Predict the output
What does it print?
city = "lima"
city.upper()
print(city)
shout = city.upper()
print(shout, city)A string method never changes the string it is called on.
Line 2 builds a new string, but nothing stores it. Line 4 stores the new string under a second name.
It prints
lima LIMA lima
upper() gives back a new string. city keeps its old value on every line, and only shout refers to the capitals.
Fix the bug
This should print the word in capitals, followed by !. It prints the word unchanged. Fix it.
With the reply tokyo, the program prints the lines below. Your program must print exactly these lines.
Example run
TOKYO!
Output
Line 2 does make the capitals. What happens to the result?
Store the result: give the name word to the new string, or call the method inside print.
word = input("Word: ")
word = word.upper()
print(word + "!")A method call on its own line builds a new string and throws it away. The result must be stored or used.
text = "the quick BROWN fox"
print(text.upper())
print(text.lower())
print(text.capitalize())
print(text.title())
print(text.swapcase())Output
THE QUICK BROWN FOX the quick brown fox The quick brown fox The Quick Brown Fox THE QUICK brown FOX
| Method | What it gives back |
|---|---|
upper() |
every letter in capitals |
lower() |
every letter in lowercase |
capitalize() |
first character capital, everything else lowercase |
title() |
the first letter of every word capital, the rest lowercase |
swapcase() |
capitals become lowercase and the other way round |
Characters that are not letters (digits, spaces, punctuation) are left alone.
The main everyday use of lower() is comparing text the way people do, ignoring capitals. Convert both sides to the same case first:
typed = "Tokyo"
stored = "TOKYO"
print(typed == stored)
print(typed.lower() == stored.lower())Output
False True
For text in any language there is an even stronger version, casefold(), built specifically for comparisons. It handles special cases that lower() leaves alone, such as the German letter ß, which is equivalent to "ss":
print("Straße".lower() == "STRASSE".lower())
print("Straße".casefold() == "STRASSE".casefold())Output
False True
Use lower() for display and casefold() when comparing text that may not be English.
title() is not as clever as it lookstitle() treats every letter that follows a non-letter as the start of a word. An apostrophe is a non-letter:
print("it's my friend's book".title())Output
It'S My Friend'S Book
It is fine for simple names, but not for general sentences.
Multiple choice
What does this print?
print("hELLO wORLD".capitalize())capitalize() and title() are different methods.
capitalize() makes the first character a capital and everything else lowercase.
The answer is: Hello world
capitalize() gives one capital at the very start and lowercases the rest, including the first letter of the second word.
Fill in the blank
Fill in the method so that the comparison ignores capitals.
typed = input("City: ")
print(typed.() == "tokyo")With the reply TOKYO, the finished program prints:
Target
True
The text on the right is all lowercase. Bring the reply to the same case.
The method name is the opposite of upper.
typed = input("City: ")
print(typed.lower() == "tokyo")Convert the reply to lowercase before comparing. casefold() does the same job and is stronger for text that may not be English.
Text from users and files often arrives with extra spaces, tabs or line breaks at the ends. Together these invisible characters are called whitespace. strip() removes whitespace from both ends:
raw = " hello world \n"
print(repr(raw))
print(repr(raw.strip()))
print(repr(raw.lstrip()))
print(repr(raw.rstrip()))Output
' hello world \n' 'hello world' 'hello world \n' ' hello world'
lstrip() trims only the left end and rstrip() only the right. None of them touches whitespace in the middle: the space between hello and world survives. (repr is used here so you can see the spaces, as in Chapter 7.)
Give strip a string, and it removes any of those characters from the ends instead of whitespace:
print("***Sale***".strip("*"))
print("$19.99".lstrip("$"))
print("...wait...".rstrip("."))Output
Sale 19.99 ...wait
To remove an exact piece of text from the front or the back, use removeprefix and removesuffix. They remove the whole piece once, or nothing at all:
print("monaco.com".removesuffix(".com"))
print("Dr. Maya Tanaka".removeprefix("Dr. "))
print("Maya Tanaka".removeprefix("Dr. "))Output
monaco Maya Tanaka Maya Tanaka
Multiple choice
What does this print?
print("text.txt".rstrip(".txt"))The argument is a set of characters: ., t and x.
rstrip keeps removing from the right end while the last character is in the set. Where does it stop?
The answer is: te
After .txt is gone, the string ends in xt, and both letters are in the set, so they go too. It stops at e.
Fix the bug
This should remove the .py ending from a file name. For notes.py it works, but for happy.py it removes too much. Fix it.
With the reply happy.py, the program prints the lines below. Your program must print exactly these lines.
Example run
happy
Output
rstrip(".py") removes every ., p and y from the right end, one character at a time.
Use the method that removes an exact ending once: its name starts with remove.
filename = input("File name: ")
print(filename.removesuffix(".py"))rstrip takes a set of characters. removesuffix removes the exact text, once, or nothing at all.
Chapter 5 gave you in, which answers is it there? with True or False. Methods answer more detailed questions.
find and indexfind gives the index where a piece of text first appears:
text = "banana bread"
print(text.find("nan"))
print(text.find("a"))
print(text.find("z"))Output
2 1 -1
"nan" starts at index 2. "a" appears several times; find reports the first. And when the text is not there, find gives -1.
index does the same job but raises an error when the text is missing, which is often safer than a quiet -1:
text = "banana bread"
print(text.index("z"))Output
Traceback (most recent call last):
File "search.py", line 2, in <module>
print(text.index("z"))
~~~~~~~~~~^^^^^
ValueError: substring not foundrfind and rindex search from the right-hand end and report the last match:
text = "banana bread"
print(text.rfind("a"))Output
10
All of them accept a starting position as a second argument: text.find("a", 2) begins looking at index 2.
counttext = "banana bread"
print(text.count("a"))
print(text.count("an"))
print(text.count("z"))Output
4 2 0
count does not count overlapping matches: "aaaa".count("aa") is 2, not 3. After each match, it carries on from the end of that match.
filename = "holiday_photo.JPG"
print(filename.startswith("holiday"))
print(filename.endswith(".jpg"))
print(filename.lower().endswith(".jpg"))Output
True False True
These are clearer than slicing (filename[-4:] == ".jpg") because you do not have to count characters. Notice the case problem again, and the fix with lower().
| Question | Tool | Gives back |
|---|---|---|
| Is it in there? | "an" in text |
True / False |
| Where is the first one? | text.find("an") |
an index, or -1 |
| Where, and stop if missing? | text.index("an") |
an index, or ValueError |
| How many? | text.count("an") |
a number, possibly 0 |
| Does it begin / end with it? | text.startswith(...), text.endswith(...) |
True / False |
Quick check
For s = "mississippi", what are s.find("ss"), s.rfind("ss"), s.count("ss") and s.find("x")?
Answer: 2, 5, 2 and -1.
Predict the output
What does it print?
text = "coffee or toffee"
print(text.find("ff"), text.rfind("ff"))
print(text.count("e"), text.find("tea"))
print(text.startswith("cof"), text.endswith("Fee"))Write the index above each character, starting at 0. find gives the first match and rfind the last.
A piece that is not there gives -1 with find. endswith is case-sensitive.
It prints
2 12 4 -1 True False
find and rfind give positions, count gives how many, and a missing piece gives -1. All of them care about capitals.
Write code
Count a letter. Ask for a sentence, then ask for one letter. Print how many times the letter is in the sentence, ignoring capitals. For Banana Bread and b the result is 2.
With the replies Banana Bread then b, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
2
Output
count is case-sensitive, so bring both the sentence and the letter to the same case first.
Chain the methods: sentence.lower().count(...), with the lowercase letter inside the brackets.
sentence = input("Sentence: ")
letter = input("Letter: ")
print(sentence.lower().count(letter.lower()))Lowering both sides makes the count ignore capitals. count gives 0 when the letter is not there.
replace(old, new) gives back a copy of the string with every occurrence of old swapped for new:
text = "I like cats. Cats are great."
print(text.replace("cats", "dogs"))
print(text.replace(" ", "_"))
print(text.replace("great", ""))Output
I like dogs. Cats are great. I_like_cats._Cats_are_great. I like cats. Cats are .
Three things to notice:
"Cats" with a capital was not replaced."" deletes.A third argument limits how many replacements are made:
print("a-b-c-d".replace("-", "+", 2))Output
a+b+c-d
replace solves the decimal-comma problem from Chapter 6:
typed = "3,75"
print(float(typed.replace(",", ".")))Output
3.75
Fill in the blank
The user typed a price with a decimal comma. Fill in the method so that float() can read it.
typed = "2,5"
price = float(typed.(",", "."))
print(price * 2)The finished program prints:
Target
5.0
The comma must become a point before float() sees the text.
Which method swaps every occurrence of one piece of text for another?
typed = "2,5"
price = float(typed.replace(",", "."))
print(price * 2)replace(",", ".") gives back a new string with a point in place of the comma, and float() accepts that.
Put the lines in order
Put the lines in order. The program removes the spaces and the hyphens from a phone number, then prints the digits and how many there are.
With the reply 555 01-42, the program in the right order prints:
Target
5550142 7
print(digits, len(digits))phone = input("Phone: ")digits = phone.replace(" ", "").replace("-", "")A name must get its value before another line uses it.
digits is built from phone, and the print line uses digits.
phone = input("Phone: ")
digits = phone.replace(" ", "").replace("-", "")
print(digits, len(digits))Replacing with the empty string deletes. Each replace gives back a new string, so the two calls can be chained.
A family of methods whose names start with is answers yes-or-no questions about the whole string:
print("2026".isdigit())
print("Python".isalpha())
print("Python3".isalpha())
print("Python3".isalnum())
print(" ".isspace())
print("HELLO".isupper(), "hello".islower())Output
True True False True True True True
| Method | True when every character is... |
|---|---|
isdigit() |
a digit |
isalpha() |
a letter (of any language) |
isalnum() |
a letter or a digit |
isspace() |
whitespace |
isupper() / islower() |
all the letters are capitals / lowercase |
Two rules catch people out:
print("New York".isalpha())
print("".isdigit())
print("-5".isdigit(), "3.5".isdigit())Output
False False False False
"New York" is not a letter, so isalpha() is False.isdigit() tells you "only digit characters", not "a valid number".Multiple choice
Exactly one of these expressions is True. Which one?
Every character must pass the test. A decimal point and a space are neither letters nor digits.
The empty string fails all of these tests.
The answer is: "Tokyo2026".isalnum()
isalnum() is True when every character is a letter or a digit. One point, one space, or no characters at all makes the test fail.
These two methods are opposites, and they are the workhorses of text processing.
split: one string into manysplit() cuts a string wherever there is whitespace and gives back the pieces:
sentence = "the quick brown fox"
words = sentence.split()
print(words)
print(len(words))
print(words[0], words[-1])Output
['the', 'quick', 'brown', 'fox'] 4 the fox
The result, shown in square brackets, is a list: an ordered collection of values, here four strings. Lists get three chapters of their own → Chapter 25. For now, three facts are enough: len counts the items, words[0] picks one with the same indexing you learned for strings, and multiple assignment can unpack them into names, as in Chapter 6.
With no argument, split() is generous: any amount of whitespace counts as one separator, and whitespace at the ends is ignored.
print(" too many spaces ".split())Output
['too', 'many', 'spaces']
Give it an argument to split on something else:
print("2026-11-23".split("-"))
print("red,green,blue".split(","))
print("one, two, three".split(", "))Output
['2026', '11', '23'] ['red', 'green', 'blue'] ['one', 'two', 'three']
With an explicit separator, split is strict. Two separators in a row produce an empty string between them:
print("a,b,,c".split(","))Output
['a', 'b', '', 'c']
Now the date problem from Chapter 8 can be solved without counting positions. This version works even if the month or day has only one digit:
year, month, day = "2026-3-7".split("-")
print(int(day), int(month), int(year))Output
7 3 2026
Two relatives are worth knowing. splitlines() splits a multi-line string into its lines. partition(sep) splits at the first separator only and always gives exactly three parts: before, the separator itself, and after.
print("line one\nline two".splitlines())
print("name=Maya=Tanaka".partition("="))Output
['line one', 'line two']
('name', '=', 'Maya=Tanaka')join: many strings into onejoin goes the other way. It is called on the glue, and it takes the pieces as its argument:
words = ["the", "quick", "brown", "fox"]
print(" ".join(words))
print("-".join(words))
print("".join(words))Output
the quick brown fox the-quick-brown-fox thequickbrownfox
" ".join(words) reads as "space, join these words". The order looks backwards at first: you might expect words.join(" "). The reason is that join is a string method, and the string doing the work is the glue.
A string is itself a sequence of characters, so join can put glue between the characters of a single string:
print(".".join("ABC"))Output
A.B.C
Splitting and re-joining is a neat way to tidy spacing. split() throws away all the extra whitespace, and " ".join(...) puts exactly one space back between the words:
messy = " too many spaces "
print(" ".join(messy.split()))Output
too many spaces
Quick check
What do "a b c".split(), "a b c".split(" ") and "+".join("a b".split()) give?
Answer: ['a', 'b', 'c']; then ['a', 'b', '', 'c'] (the two spaces in a row leave an empty string between them); then "a+b".
Put the lines in order
Put the lines in order. The program turns a date typed as day/month/year into the form year-month-day.
With the reply 23/11/2026, the program in the right order prints:
Target
2026-11-23
date = input("Date: ")print(year + "-" + month + "-" + day)day, month, year = date.split("/")The reply must arrive before it can be cut into pieces.
The print line uses the three names that the split line creates.
date = input("Date: ")
day, month, year = date.split("/")
print(year + "-" + month + "-" + day)split("/") gives three pieces, and multiple assignment gives each piece a name. The last line joins them in the new order.
Fill in the blank
Fill in the method that glues the words together with a comma and a space.
words = "red green blue".split()
print(", ".(words))The finished program prints:
Target
red, green, blue
This method is called on the glue, and the pieces go inside the brackets.
It is the opposite of split.
words = "red green blue".split()
print(", ".join(words))", ".join(words) reads as: comma and space, join these words. The glue goes between the pieces only.
Multiple choice
What does this print?
print("2,,5".split(","))With a separator in the brackets, split is strict.
What is between the two commas? Nothing at all, and split reports that too.
The answer is: ['2', '', '5']
Two separators in a row leave an empty string between them. Only split() with no argument treats a run of whitespace as one separator.
Write code
Tidy the spaces. Ask for a sentence that may have extra spaces anywhere. Print two lines: first the sentence with exactly one space between the words and no spaces at the ends, then the number of words.
With the reply too many spaces , the program prints the lines below. Your program must print exactly these lines.
Example run
too many spaces 3
Output
split() with no argument throws away all the extra whitespace and gives the words.
" ".join(words) puts exactly one space back between the words. len(words) counts them.
sentence = input("Sentence: ")
words = sentence.split()
print(" ".join(words))
print(len(words))Splitting and joining again is the standard way to tidy spacing. The list from split() also gives the word count.
These methods pad a string with spaces (or another character) to reach a given width:
print("[" + "left".ljust(10) + "]")
print("[" + "right".rjust(10) + "]")
print("[" + "middle".center(10) + "]")
print("[" + "title".center(11, "*") + "]")
print("42".zfill(5), "-42".zfill(5))Output
[left ] [ right] [ middle ] [***title***] 00042 -0042
zfill pads a number-in-text with leading zeros and keeps a minus sign at the front. If the string is already as wide as you ask, all of these give it back unchanged; they never cut text off. F-strings can do the same alignment in a more compact way → Chapter 16.
Predict the output
What does it print? Type every space exactly.
print("7".zfill(3) + "|" + "ok".rjust(4) + "|")
print("hi".center(6, "-"))
print("long word".ljust(4) + "!")zfill(3) pads with zeros on the left to width 3. rjust(4) pads with spaces on the left to width 4.
When the string is already wider than the width you ask for, it comes back unchanged.
It prints
007| ok| --hi-- long word!
The padding methods add characters until the width is reached. They never cut text off.
Since each method gives back a string, you can call another method directly on the result, and another on that. This is called method chaining. It runs from left to right:
raw = " mAYA tanaka "
clean = raw.strip().title()
print(clean)Output
Maya Tanaka
" mAYA tanaka "
.strip() ──► "mAYA tanaka"
.title() ──► "Maya Tanaka"
The order matters. Each step works on whatever the previous step produced:
print("Hello World".replace("World", "there").upper())
print("Hello World".upper().replace("World", "there"))Output
HELLO THERE HELLO WORLD
In the second line, by the time replace runs, the text is "HELLO WORLD". The piece "World", with its lowercase letters, is no longer in it, so nothing is replaced.
Fix the bug
The user types a code made of lowercase letters and digits. The program should replace every x with a hyphen and print the result in capitals. For x7xk it should print -7-K, but no hyphen appears. Fix it.
With the reply x7xk, the program prints the lines below. Your program must print exactly these lines.
Example run
-7-K
Output
A chain runs from left to right. What does the text look like when replace starts its work?
After upper(), there is no lowercase x left to find. Change the order of the two calls.
code = input("Code: ")
print(code.replace("x", "-").upper())Each step works on what the step before produced. replace is case-sensitive, so it must run before upper().
Put the lines in order
Put the lines in order: get the reply, clean it, cut it at the @ sign, then print the two parts.
With the reply Maya@Example.COM , the program in the right order prints:
Target
maya example.com
raw = input("Email: ")print(name, domain)clean = raw.strip().lower()name, sign, domain = clean.partition("@")Follow the names: each line uses a name that an earlier line created.
clean is made from raw, and partition is called on clean.
raw = input("Email: ")
clean = raw.strip().lower()
name, sign, domain = clean.partition("@")
print(name, domain)Clean the reply as soon as it arrives. partition("@") always gives three parts: before, the separator, and the rest.
So far, a string has been "a row of characters". Now for what a character actually is.
Computers store only numbers. To store text, everyone must agree on a table that says which number means which character. Early computers used a table called ASCII, with 128 entries: enough for English letters, digits and common punctuation, and nothing else. Dozens of incompatible extra tables appeared for other languages, and text sent between countries regularly turned into nonsense.
Unicode is the fix: one table for all of humanity's writing. It gives every character a unique number called its code point. It covers more than 150 000 characters: every modern script, ancient ones, mathematical and musical symbols, and emojis. Python strings are sequences of Unicode code points.
Two built-in functions move between characters and their numbers:
ord(character) gives the code point of one character.chr(number) gives the character for a code point.print(ord("A"), ord("a"), ord("0"), ord(" "))
print(chr(65), chr(97), chr(8364), chr(128075))Output
65 97 48 32 A a € 👋
They are exact opposites: chr(ord("x")) is "x".
Code points are often written in hexadecimal with U+ in front: A is U+0041, and € is U+20AC. That is the number you put after \u in a string, as in Chapter 7.
48 ─ 57 digits 0 1 2 3 4 5 6 7 8 9 65 ─ 90 capitals A B C ... X Y Z 97 ─ 122 lowercase a b c ... x y z
The digits are in order, the capitals are in order, and the lowercase letters are in order. This explains the string comparisons in Chapter 5 ("Z" < "a" because 90 < 97), and it allows arithmetic on letters:
print(chr(ord("a") + 1))
print(ord("e") - ord("a"))
print(ord("a") - ord("A"))
print(chr(ord("m") - 32))Output
b 4 32 M
a is chr(ord("a") + 1).e is 4 places after a.upper() does for English letters.It also gives you a digit's value without int(): ord("7") - ord("0") is 7.
Shifting each letter a fixed number of places along the alphabet is one of the oldest ciphers, used by Julius Caesar. For one letter:
letter = "h"
shift = 3
position = ord(letter) - ord("a") # h is at position 7 (a is 0)
new_position = (position + shift) % 26 # wrap around after z
print(chr(ord("a") + new_position))Output
k
The % 26 makes the alphabet wrap around, the clock-style use of the remainder from Chapter 4: shifting y by 3 gives b. With a loop you can encode a whole message → Chapter 14.
Quick check
What are chr(ord("C") + 2), ord("9") - ord("0") and chr(ord("b") - 32)?
Answer: "E", 9 and "B".
Predict the output
What does it print?
print(ord("C") - ord("B"), chr(ord("p") + 2))
print(chr(ord("T") + 32), ord("8") - ord("0"))Letters are in order in the table, so neighbours differ by 1.
Every lowercase letter is exactly 32 above its capital. The digits are in order too.
It prints
1 r t 8
ord gives the code point and chr goes back. The ordered layout of the table makes this arithmetic work.
Fill in the blank
Fill in the function so that the program prints the capital form of the letter.
letter = "k"
print(chr((letter) - 32))The finished program prints:
Target
K
You can subtract 32 from a number only, not from a character.
Which function gives the code point of one character?
letter = "k"
print(chr(ord(letter) - 32))ord(letter) gives the code point, subtracting 32 moves to the capital, and chr turns the number back into a character.
Write code
Letter position. Ask for one capital English letter. Print two lines: first its code point, then its position in the alphabet (1 for the first letter, 26 for Z).
With the reply C, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
67 3
Output
ord() gives the code point of the letter.
The capitals start at code point 65, so the first letter must give 1. Which number do you subtract?
letter = input("Capital letter: ")
code = ord(letter)
print(code)
print(code - 64)The capitals are in order from 65 to 90, so the code point minus 64 is the position in the alphabet.
A code point is an abstract number. To save text in a file or send it over a network, those numbers must be turned into bytes, the 8-bit units that disks and networks actually carry. A byte can only hold a value from 0 to 255, but code points go beyond a million. The set of rules for packing code points into bytes is called an encoding.
The encoding used almost everywhere today is UTF-8. Its clever idea is that different characters use different numbers of bytes:
| Characters | Bytes each in UTF-8 |
|---|---|
| English letters, digits, basic punctuation (the old ASCII set) | 1 |
| Accented Latin letters, Greek, Cyrillic, Arabic, Hebrew | 2 |
Most other scripts, including Chinese, Japanese, Korean, Devanagari; € |
3 |
| Emojis and rarer characters | 4 |
The encode method turns a str into bytes, and decode turns bytes back into a str:
word = "café"
data = word.encode("utf-8")
print(data)
print(type(data))
print(len(word), len(data))
print(data.decode("utf-8"))Output
b'caf\xc3\xa9' <class 'bytes'> 4 5 café
data is a new type, bytes: a sequence of raw byte values. Python shows it with a b in front. Bytes that happen to match ASCII characters are shown as those characters (c, a, f); the rest are shown in hexadecimal (\xc3\xa9 is the two bytes that encode é).
The key lesson: the number of characters and the number of bytes are different things. "café" has 4 characters but takes 5 bytes.
print(len("A".encode("utf-8")))
print(len("é".encode("utf-8")))
print(len("€".encode("utf-8")))
print(len("👋".encode("utf-8")))Output
1 2 3 4
This matters whenever there is a size limit measured in bytes, such as a database column or a text message.
Older encodings cannot represent every character. Ask ASCII to encode a character outside its 128 and you get an error:
print("café".encode("ascii"))Output
Traceback (most recent call last):
File "encode.py", line 1, in <module>
print("café".encode("ascii"))
~~~~~~~~~~~~~^^^^^^^^^
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 3: ordinal not in range(128)Read it piece by piece: the ASCII encoding cannot handle the character é (code point e9 in hexadecimal) at index 3, because its number is not below 128.
The opposite mistake is decoding bytes with the wrong encoding. That often does not raise an error at all. It produces garbage such as café in place of café. If you have ever seen text like that on a web page or in an email, you have seen an encoding mix-up.
Multiple choice
What does this print?
print(len("señor".encode("utf-8")))encode gives bytes, so len counts bytes here, not characters.
The plain English letters take 1 byte each. An accented Latin letter takes 2.
The answer is: 6
Four plain letters take one byte each and ñ takes two. Characters and bytes are different counts.
Predict the output
What does it print?
word = "crème"
data = word.encode("utf-8")
print(len(word), len(data))
print(data.decode("utf-8") == word)len(word) counts characters and len(data) counts bytes. è takes two bytes.
decode is the exact opposite of encode when both use the same encoding.
It prints
5 6 True
The word has five characters and needs six bytes. Decoding the bytes with the same encoding gives the original string back.
Unicode has a few surprises that can make two strings look identical on screen but compare as different.
The letter é can be stored as one code point (U+00E9), or as a plain e followed by a separate "combining accent" code point (U+0301) that the screen draws on top of it:
one = "café"
two = "café"
print(one, two)
print(one == two)
print(len(one), len(two))Output
café café False 4 5
They display the same, but they are different sequences of code points, so == says False. The fix is normalisation: converting both to one standard spelling before comparing. The standard unicodedata module does it (modules are explained in → Chapter 42):
import unicodedata
one = "café"
two = "café"
print(unicodedata.normalize("NFC", one) == unicodedata.normalize("NFC", two))Output
True
This uses import, which is taught in Chapter 17.
"NFC" is the name of the most common standard form: "combine wherever possible".
len counts code points, and some things that look like a single symbol are built from several. A flag is two "regional indicator" letters. A thumbs-up with a skin tone is the thumbs-up followed by a colour modifier:
print(len("\N{REGIONAL INDICATOR SYMBOL LETTER J}\N{REGIONAL INDICATOR SYMBOL LETTER P}"))
print(len("\N{THUMBS UP SIGN}\N{EMOJI MODIFIER FITZPATRICK TYPE-4}"))Output
2 2
Each of those is drawn as one picture on a phone, the flag of Japan and a thumbs-up, but each has length 2. Slicing or reversing such text can split a symbol in half. For everyday text this rarely matters, but it is good to know that "what the user sees as one character" and "one code point" are not always the same thing.
Multiple choice
A flag emoji is drawn as one picture, but len() gives 2 for it. What does len() count in a string?
A Python string is a sequence of numbers from the Unicode table.
One picture on the screen can be built from several of those numbers.
The answer is: Code points
len counts code points. Some symbols that look like one character are made of two or more code points.
You do not have to memorise fifty methods. Three ways to explore:
help(str.split) shows the documentation for one method, and help(str) shows them all.dir("") lists the names of everything a string can do.Terminal
>>> help(str.zfill)
Help on method descriptor zfill:
zfill(self, width, /) unbound builtins.str method
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.When you want to do something to a string, assume a method for it already exists, and look before writing your own.
| The mistake | What you see | The fix |
|---|---|---|
Not storing the result: text.upper() on its own line |
text is unchanged |
text = text.upper() |
Forgetting the brackets: text.upper |
<built-in method upper of str object ...> |
text.upper() |
Calling a method as a function: upper(text) |
NameError: name 'upper' is not defined |
text.upper() |
| Comparing without matching case | "Yes" == "yes" is False |
Compare .lower() of both sides |
strip(".com") to remove an ending |
Extra letters vanish (mona) |
removesuffix(".com") |
Using the result of find without checking |
text[-1] when not found |
Check for -1, or use index |
Join the wrong way round: words.join(" ") |
AttributeError: 'list' object has no attribute 'join' |
" ".join(words) |
"12.5".isdigit() to test for a number |
False |
isdigit only means "all digit characters" |
A method on a number: (42).upper() |
AttributeError: 'int' object has no attribute 'upper' |
Convert with str() first |
| Assuming characters equal bytes | A length that looks wrong | len(text) counts characters; len(text.encode()) counts bytes |
AttributeError is new. An attribute is anything that comes after a dot. The error means "this type of value has nothing by that name". When you see it, check the type of the value on the left of the dot.
Fix the bug
This program stops with a NameError. Fix it so that it prints the city in capitals.
With the reply tokyo, the program prints the lines below. Your program must print exactly these lines.
Example run
TOKYO
Output
upper is not a function that stands on its own. It belongs to strings.
Write the value first, then a dot, then the method name and brackets.
city = input("City: ")
print(city.upper())A method lives inside the type, so it is called on a value with a dot: city.upper().
Questions with a Check button are checked on this page. Use the hints when you are stuck: the last step always shows the answer. The other questions show the book's answer, so that you can compare.
Check yourself
How does calling a method differ from calling a function? Give one example of each.
A function is called with the value inside the brackets: len("hi"). A method is called on a value with a dot: "hi".upper().
Check yourself
After city = "tokyo" and city.capitalize(), what does city refer to? Why?
Still "tokyo". The method gave back the new string "Tokyo", but it was not stored, and strings cannot be changed in place.
Check yourself
What is the difference between capitalize() and title()?
capitalize() makes only the very first character a capital and lowercases the rest. title() capitalises the first letter of every word.
Check yourself
What does strip() remove? Does it remove spaces in the middle of a string?
Whitespace (spaces, tabs, new lines) at both ends. It never touches the middle.
Check yourself
Why does "hello.txt".rstrip(".txt") give "hello" but "next.txt".rstrip(".txt") give "ne"?
The argument is a set of characters: ., t and x. rstrip removes from the end for as long as the last character is one of them. "hello.txt" stops at o. "next.txt" loses .txt and then also the xt of next.
Check yourself
What do find and index each do when the text is not found? Why can -1 cause a hidden bug?
find gives -1; index raises ValueError. -1 is a valid index (the last character), so using it without checking silently reads the wrong character.
Check yourself
Why is "".isalpha() False?
The is... methods need at least one character, and every character must pass. An empty string has none.
Check yourself
In ", ".join(names), which value is the glue and which holds the pieces?
", " is the glue; names holds the pieces.
Check yourself
What do ord and chr do? What is chr(ord("A") + 25)?
ord gives a character's code point; chr gives the character for a code point. chr(ord("A") + 25) is "Z".
Check yourself
Why can len(text) and len(text.encode("utf-8")) be different?
len(text) counts characters (code points). In UTF-8, characters outside the basic ASCII set take 2, 3 or 4 bytes each.
Predict the output
s = "Hello, World"
print(s.lower().count("o"))
print(s.replace("l", "L", 2))
print(s.find("o"), s.rfind("o"), s.find("O"))Line 1 counts in the lowercase copy. Line 2 has a third argument: a limit on the number of replacements.
find reports the first match and rfind the last. Both are case-sensitive, and a missing piece gives -1.
It prints
2 HeLLo, World 4 8 -1
"hello, world" has two os. find("O") is case-sensitive, so the capital is not found.
s = "Hello, World"
print(s.lower().count("o"))
print(s.replace("l", "L", 2))
print(s.find("o"), s.rfind("o"), s.find("O"))Output
2 HeLLo, World 4 8 -1
Predict the output
s = " Data Science "
s.strip()
print(len(s))
s = s.strip()
print(len(s), s.split())Look at line 2. Is the result of strip() stored anywhere?
Count the characters with the two spaces at each end, then without them. split() gives a list, shown in square brackets.
It prints
16 12 ['Data', 'Science']
The first strip() is thrown away, so the length is still 16.
s = " Data Science "
s.strip()
print(len(s))
s = s.strip()
print(len(s), s.split())Output
16 12 ['Data', 'Science']
Predict the output
print("a-b-c".split("-"))
print("+".join("a-b-c".split("-")))
print("a--b".split("-"))
print(" ".join(["x"]))split("-") is strict: two separators in a row leave an empty string between them.
join puts the glue between the pieces only. How many gaps does one piece have?
It prints
['a', 'b', 'c'] a+b+c ['a', '', 'b'] x
Two separators in a row give an empty string. Joining a single item adds no glue.
print("a-b-c".split("-"))
print("+".join("a-b-c".split("-")))
print("a--b".split("-"))
print(" ".join(["x"]))Output
['a', 'b', 'c'] a+b+c ['a', '', 'b'] x
Predict the output
print("42".isdigit(), "4 2".isdigit(), "four".isalpha(), "R2D2".isalnum())
print("python".upper().lower().title().swapcase())The is... methods need every character to pass. A space is not a digit.
Follow the chain from left to right and write down the value after each step.
It prints
True False True True pYTHON
The chain: PYTHON, python, Python, then swapcase gives pYTHON.
print("42".isdigit(), "4 2".isdigit(), "four".isalpha(), "R2D2".isalnum())
print("python".upper().lower().title().swapcase())Output
True False True True pYTHON
Predict the output
print(ord("d") - ord("a"), chr(ord("x") + 2), chr(ord("5") + 1))
print(len("naïve"), len("naïve".encode("utf-8")))Letters and digits are in order in the Unicode table, so adding 1 gives the next character.
len of a string counts characters. In UTF-8, an accented Latin letter takes two bytes.
It prints
3 z 6 5 6
ï takes two bytes in UTF-8.
print(ord("d") - ord("a"), chr(ord("x") + 2), chr(ord("5") + 1))
print(len("naïve"), len("naïve".encode("utf-8")))Output
3 z 6 5 6
Fix the bug
This should print the name in capitals. It prints it unchanged.
The program prints the lines below. Your program must print exactly these lines.
Example run
MAYA
Output
A string method never changes the string. It gives back a new one.
Nobody catches the result on line 2. Store it in name.
name = "maya"
name = name.upper()
print(name)Store the result.
name = "maya"
name = name.upper()
print(name)Output
MAYA
Fix the bug
This should print True for any way of typing "quit". It prints False for QUIT.
The program prints the lines below. Your program must print exactly these lines.
Example run
True
Output
== cares about capitals. "QUIT" and "quit" are different strings.
Change command to one fixed case before you compare it.
command = "QUIT"
print(command.lower() == "quit")Lower the text before comparing.
command = "QUIT"
print(command.lower() == "quit")Output
True
Fix the bug
This should join the words with commas. It crashes.
The program prints the lines below. Your program must print exactly these lines.
Example run
red, green, blue
Output
join is a string method. Which value here is a string, and which one is a list?
The glue goes in front of the dot, and the pieces go inside the brackets.
words = ["red", "green", "blue"]
print(", ".join(words))join is a method of the glue string.
words = ["red", "green", "blue"]
print(", ".join(words))Output
red, green, blue
Fix the bug
This should remove the .org ending and print doctor. It prints doct.
The program prints the lines below. Your program must print exactly these lines.
Example run
doctor
Output
The argument of rstrip is a set of characters, not a word. Which letters at the end of doctor are in that set?
One method removes an exact ending, once, or nothing at all.
site = "doctor.org"
print(site.removesuffix(".org"))rstrip removes a set of characters. removesuffix removes exact text.
site = "doctor.org"
print(site.removesuffix(".org"))Output
doctor
Fix the bug
This should print the letter that follows the @ sign, or say something sensible if there is none. For "no at sign" it prints n.
Keep text = "no at sign". Print the repr() of the character that follows the @ sign, so that "no character" is shown as an empty string in quotes.
The program prints the lines below. Your program must print exactly these lines.
Example run
''
Output
When find gives -1, what is position + 1? Which character sits at that index?
partition("@") always gives three parts. When there is no @, the third part is an empty string, and a slice such as [:1] of an empty string is safe.
text = "no at sign"
before, sign, rest = text.partition("@")
print(repr(rest[:1]))When find gives -1, position + 1 is 0, the first character. partition avoids the problem: if there is no @, the part after it is an empty string, and a slice of an empty string is safe.
text = "no at sign"
before, sign, after = text.partition("@")
print(repr(after[:1]))
text = "maya@example.com"
before, sign, after = text.partition("@")
print(repr(after[:1]))Output
'' 'e'
Write code · Easy
Shout and whisper. Ask for a sentence and print it in capitals, in lowercase, and with a capital on every word.
Print three lines: the sentence in capitals, then in lowercase, then with a capital on every word (the title() form).
With the reply strings are fun, the program prints the lines below. Your program must print exactly these lines.
Example run
STRINGS ARE FUN strings are fun Strings Are Fun
Output
Each form is one method call on the sentence.
The three methods are upper(), lower() and title(). Print each result on its own line.
sentence = input("Sentence: ")
print(sentence.upper())
print(sentence.lower())
print(sentence.title())sentence = input("Sentence: ")
print(sentence.upper())
print(sentence.lower())
print(sentence.title())Output
Sentence: strings are fun STRINGS ARE FUN strings are fun Strings Are Fun
Write code · Easy
Word count. Ask for a sentence and print how many words it has.
With the reply the quick brown fox jumps, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
5
Output
Which method cuts a sentence into words wherever there is whitespace?
split() gives a list, and len() counts its items.
sentence = input("Sentence: ")
print(len(sentence.split()))sentence = input("Sentence: ")
print(len(sentence.split()))Output
Sentence: the quick brown fox jumps 5
Write code · Easy
Clean yes. Ask a yes-or-no question and print True if the user typed "yes" in any mix of capitals and with any spaces around it.
Print only True or False.
With the reply YeS , the program prints the lines below. Your program must print exactly these lines.
Example run
True
Output
Clean the reply first: trim the ends and make it lowercase.
Chain strip() and lower(), then compare the result with "yes" using ==.
reply = input("Save the file? ").strip().lower()
print(reply == "yes")reply = input("Save the file? ").strip().lower()
print(reply == "yes")Output
Save the file? YeS True
Write code · Medium
File parts. Given filename = "summer_holiday.final.JPG", print the name without the extension and the extension in lowercase without its dot.
Print two lines: the name without the extension first, then the extension.
The program prints the lines below. Your program must print exactly these lines.
Example run
summer_holiday.final jpg
Output
Slice the text before the last dot, and the text after it.
rfind finds the last dot.
filename = "summer_holiday.final.JPG"
dot = filename.rfind(".")
print(filename[:dot])
print(filename[dot + 1:].lower())rfind(".") finds the last dot, which is the one before the extension.
filename = "summer_holiday.final.JPG"
dot = filename.rfind(".")
print(filename[:dot])
print(filename[dot + 1:].lower())Output
summer_holiday.final jpg
Write code · Medium
Censor. Ask for a sentence and a word, and print the sentence with every occurrence of that word replaced by stars, as many stars as the word has letters.
Ask for the sentence first, then the word. Print only the changed sentence.
With the replies the cat sat on the mat then the, the program prints the lines below. Your program must print exactly these lines.
Example run
*** cat sat on *** mat
Output
"*" * 3 builds a row of three stars. Which function gives the number of letters in the word?
Use replace(word, stars). It replaces every match.
sentence = input("Sentence: ")
word = input("Word to hide: ")
print(sentence.replace(word, "*" * len(word)))sentence = input("Sentence: ")
word = input("Word to hide: ")
print(sentence.replace(word, "*" * len(word)))Output
Sentence: the cat sat on the mat Word to hide: the *** cat sat on *** mat
Write code · Medium
Slug. Turn a title such as " My First Blog Post! " into a web-friendly "slug": my-first-blog-post. Trim it, lowercase it, remove the !, and put hyphens between the words.
Start from title = " My First Blog Post! " and print only the slug.
The program prints the lines below. Your program must print exactly these lines.
Example run
my-first-blog-post
Output
Do the steps in the order of the task: strip(), lower(), then replace("!", "").
After that, split() gives the words, and "-".join(...) puts hyphens between them.
title = " My First Blog Post! "
slug = "-".join(title.strip().lower().replace("!", "").split())
print(slug)title = " My First Blog Post! "
slug = "-".join(title.strip().lower().replace("!", "").split())
print(slug)Output
my-first-blog-post
Reading left to right: trim, lowercase, delete the !, split into words, and join the words with hyphens.
Write code · Hard
Next letter. Ask for one lowercase letter and print the letter that comes 5 places later in the alphabet, wrapping round from z to the start. For x the answer is c.
Print only the new letter.
With the reply x, the program prints the lines below. Your program must print exactly these lines.
Example run
c
Output
Turn the letter into its position in the alphabet first, with ord. The first letter is at position 0.
Add 5, then use % 26 to wrap round. Go back to a letter with chr.
letter = input("A lowercase letter: ")
position = ord(letter) - ord("a")
print(chr(ord("a") + (position + 5) % 26))letter = input("A lowercase letter: ")
position = ord(letter) - ord("a")
print(chr(ord("a") + (position + 5) % 26))Output
A lowercase letter: x c
x is at position 23. Adding 5 gives 28, and 28 % 26 is 2, the position of c.
Write code · Hard
Time adder. Ask for a time in the form hh:mm, such as 09:45, and a number of minutes to add. Print the new time in the same two-digit form. For 09:45 plus 30 the answer is 10:15. Assume the result stays within the same day.
Ask for the time first, then the minutes to add. Print only the new time, in the form hh:mm.
With the replies 09:45 then 30, the program prints the lines below. Your program must print exactly these lines.
Example run
10:15
Output
The two pieces from split(":") are text. Convert each one with int() before any maths.
split(":"), convert to total minutes, add, then use // and %, and zfill for the leading zeros.
hours, minutes = input("Time (hh:mm): ").split(":")
extra = int(input("Minutes to add: "))
total = int(hours) * 60 + int(minutes) + extra
new_hours = str(total // 60).zfill(2)
new_minutes = str(total % 60).zfill(2)
print(f"{new_hours}:{new_minutes}")hours, minutes = input("Time (hh:mm): ").split(":")
extra = int(input("Minutes to add: "))
total = int(hours) * 60 + int(minutes) + extra
new_hours = str(total // 60).zfill(2)
new_minutes = str(total % 60).zfill(2)
print(f"{new_hours}:{new_minutes}")Output
Time (hh:mm): 09:45 Minutes to add: 30 10:15
Write code · Hard
Byte budget. A text message service allows 20 bytes in UTF-8. For each of the strings "Good morning, team!", "Café à 9 h, d'accord?" and "OK 👍👍👍👍", print the number of characters, the number of bytes, and whether it fits.
Print one line for each string, in the order given: the number of characters, the number of bytes, then True or False, with one space between them. You can copy the three strings from the question.
The program prints the lines below. Your program must print exactly these lines.
Example run
19 19 True 21 23 False 7 19 True
Output
len(text) counts characters. len(text.encode("utf-8")) counts bytes.
The message fits when the number of bytes is <= 20. Printing that comparison shows True or False.
text = "Good morning, team!"
print(len(text), len(text.encode("utf-8")), len(text.encode("utf-8")) <= 20)
text = "Café à 9 h, d'accord?"
print(len(text), len(text.encode("utf-8")), len(text.encode("utf-8")) <= 20)
text = "OK 👍👍👍👍"
print(len(text), len(text.encode("utf-8")), len(text.encode("utf-8")) <= 20)text = "Good morning, team!"
print(len(text), len(text.encode("utf-8")), len(text.encode("utf-8")) <= 20)
text = "Café à 9 h, d'accord?"
print(len(text), len(text.encode("utf-8")), len(text.encode("utf-8")) <= 20)
text = "OK 👍👍👍👍"
print(len(text), len(text.encode("utf-8")), len(text.encode("utf-8")) <= 20)Output
19 19 True 21 23 False 7 19 True
The last message has only 7 characters but needs 19 bytes, because each emoji takes four.
Write code
Product code. Ask for a product name, then for a product number. Print one line: the first three letters of the name in capitals, a hyphen, and the number padded with zeros on the left to four digits. Ignore spaces at the ends of both replies. For keyboard and 42 the line is KEY-0042.
With the replies keyboard then 42, the program prints the lines below. Your program must print exactly these lines.
Example run
KEY-0042
Output
Trim each reply with strip() as soon as it arrives. A slice gives the first three letters.
Keep the number as text: zfill(4) pads it with zeros. Join the parts with +.
name = input("Product: ").strip()
number = input("Number: ").strip()
print(name[:3].upper() + "-" + number.zfill(4))The program combines a slice, upper(), strip() and zfill(). The number stays text, because padding is a job for a string method.
Project
Print a parcel label. A shipping desk types the details of a parcel carelessly, with stray spaces and random capitals. Write a program that asks four questions, in this order:
2,5Trim the spaces at the ends of every reply. Then print exactly five lines:
Name: and the name, with one space between the words and a capital on every word (the title() form)City: and the city in capitalsParcel: and the first three letters of the city in capitals, a hyphen, and the parcel number padded with zeros to five digitsWeight: and the weight with a point in place of the comma, then a space and kg=Clean each reply on the line where it arrives, as section 9.15 did, and build the lines from the clean values.
With the replies leo MARTIN then lima then 42 then 2,5, the program prints the lines below. Your program must print exactly these lines.
Example run
Name: Leo Martin City: LIMA Parcel: LIM-00042 Weight: 2.5 kg =======Leo Martin=======
Output
For the name, split() throws away every extra space, " ".join(...) puts one space back, and title() fixes the capitals.
The city needs strip() and upper(). Its first three letters are a slice. The parcel number stays text, so zfill(5) can pad it.
replace(",", ".") fixes the weight. For the last line, call center(24, "=") on the clean name.
name = " ".join(input("Receiver: ").split()).title()
city = input("City: ").strip().upper()
number = input("Parcel number: ").strip()
weight = input("Weight in kg: ").strip().replace(",", ".")
print(f"Name: {name}")
print(f"City: {city}")
print(f"Parcel: {city[:3]}-{number.zfill(5)}")
print(f"Weight: {weight} kg")
print(name.center(24, "="))Every reply is cleaned with a short method chain on the line where it arrives. After that, each output line needs only one or two tools: a slice, zfill, replace or center.