Core by Critic
ChaptersStreak: 0 days

Ultimate Core Python · Chapter 9

Strings III: String Methods and Unicode

This lesson goes with Episode 9 of the Ultimate Core Python course on the Core by Critic channel on YouTube.

0 of 0 done

9.1 What a method is

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.

The golden rule: methods give back a new string

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

Do not forget the brackets

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

Show the answer

Answer: maya. The method built "MAYA" but the result was not stored. name = name.upper() would change what name refers to.

Practice 9.1

Predict the output

What does it print?

city = "lima"
city.upper()
print(city)
shout = city.upper()
print(shout, city)

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!

9.2 Changing case

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.

Comparing without caring about case

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 looks

title() 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.

Practice 9.2

Multiple choice

What does this print?

print("hELLO wORLD".capitalize())
Choose one answer

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

9.3 Trimming the ends

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

Stripping other characters

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

Practice 9.3

Multiple choice

What does this print?

print("text.txt".rstrip(".txt"))
Choose one answer

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

9.4 Searching inside a string

Chapter 5 gave you in, which answers is it there? with True or False. Methods answer more detailed questions.

Where is it? find and index

find 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 found

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

How many? count

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

Does it start or end with...?

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

Show the answer

Answer: 2, 5, 2 and -1.

Practice 9.4

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

9.5 Replacing

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:

  • It is case-sensitive: "Cats" with a capital was not replaced.
  • It replaces all matches, not just the first.
  • Replacing with the empty string "" 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

Practice 9.5

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

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
  1. print(digits, len(digits))
  2. phone = input("Phone: ")
  3. digits = phone.replace(" ", "").replace("-", "")

9.6 Asking what a string contains

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
  • Every character must pass. The space in "New York" is not a letter, so isalpha() is False.
  • The empty string fails all of these tests. With no characters, there is nothing to say yes about.
  • A minus sign and a decimal point are not digits, as you saw in Chapter 6. isdigit() tells you "only digit characters", not "a valid number".

Practice 9.6

Multiple choice

Exactly one of these expressions is True. Which one?

Choose one answer

9.7 Splitting and joining

These two methods are opposites, and they are the workhorses of text processing.

split: one string into many

split() 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 one

join 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

Split and join together

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?

Show the answer

Answer: ['a', 'b', 'c']; then ['a', 'b', '', 'c'] (the two spaces in a row leave an empty string between them); then "a+b".

Practice 9.7

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
  1. date = input("Date: ")
  2. print(year + "-" + month + "-" + day)
  3. day, month, year = date.split("/")

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

Multiple choice

What does this print?

print("2,,5".split(","))
Choose one answer

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

9.8 Lining text up

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.

Practice 9.8

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

9.9 Chaining methods

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.

Practice 9.9

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

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 [email protected] , the program in the right order prints:

Target

maya example.com
  1. raw = input("Email: ")
  2. print(name, domain)
  3. clean = raw.strip().lower()
  4. name, sign, domain = clean.partition("@")

9.10 Characters are numbers: Unicode

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.

The table has a helpful layout

   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
  • The letter after a is chr(ord("a") + 1).
  • e is 4 places after a.
  • Every lowercase letter is exactly 32 above its capital, so subtracting 32 converts to uppercase. That is what upper() does for English letters.

It also gives you a digit's value without int(): ord("7") - ord("0") is 7.

A tiny secret code

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

Show the answer

Answer: "E", 9 and "B".

Practice 9.10

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

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

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

9.11 From characters to bytes: encoding

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.

When encoding goes wrong

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.

Practice 9.11

Multiple choice

What does this print?

print(len("señor".encode("utf-8")))
Choose one answer

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)

9.12 When equal-looking strings are not equal

Unicode has a few surprises that can make two strings look identical on screen but compare as different.

One character, two spellings

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

One picture, several code points

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.

Practice 9.12

Multiple choice

A flag emoji is drawn as one picture, but len() gives 2 for it. What does len() count in a string?

Choose one answer

9.13 Finding the method you need

You do not have to memorise fifty methods. Three ways to explore:

  • In VS Code, type a string variable's name followed by a dot. A list of every method appears, and you can scroll through it.
  • In the shell, 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.

9.14 Common mistakes

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.

Practice 9.14

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

9.15 Putting it together

9.16 How methods and Unicode work

+ Practice

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.

Questions

Check yourself

How does calling a method differ from calling a function? Give one example of each.

Show the answer

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?

Show the answer

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()?

Show the answer

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?

Show the answer

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

Show the answer

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?

Show the answer

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?

Show the answer

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?

Show the answer

", " is the glue; names holds the pieces.

Check yourself

What do ord and chr do? What is chr(ord("A") + 25)?

Show the answer

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?

Show the answer

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

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

Predict the output

s = "  Data Science  "
s.strip()
print(len(s))
s = s.strip()
print(len(s), s.split())

Predict the output

print("a-b-c".split("-"))
print("+".join("a-b-c".split("-")))
print("a--b".split("-"))
print(" ".join(["x"]))

Predict the output

print("42".isdigit(), "4 2".isdigit(), "four".isalpha(), "R2D2".isalnum())
print("python".upper().lower().title().swapcase())

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

Fix the bug

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

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

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

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

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

''

Coding problems

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

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

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

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

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

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

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

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

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

More practice

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

Chapter project: Parcel label

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:

  1. the name of the receiver (one or more words)
  2. the city
  3. the parcel number (digits only)
  4. the weight in kg, typed with a decimal comma, such as 2,5

Trim 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 capitals
  • Parcel: and the first three letters of the city in capitals, a hyphen, and the parcel number padded with zeros to five digits
  • Weight: and the weight with a point in place of the comma, then a space and kg
  • the clean name from the first line, centred in a width of 24 and padded with =

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=======