Core by Critic
ChaptersStreak: 0 days

Ultimate Core Python · Chapter 7

Strings I: Making Strings

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

0 of 0 done

7.1 What a string is

You have used strings since your first program. Here is the precise definition: a string is a sequence of characters. Sequence means the characters are in a definite order, first to last. The type is called str.

word = "Python"
print(word)
print(type(word))

Output

Python
<class 'str'>

The quote marks are not part of the string. They are delimiters: they tell Python where the string starts and where it ends, like the covers of a book. The string itself is the six characters P, y, t, h, o, n.

Everything between the quotes counts, including spaces:

print("Hello")
print(" Hello ")
print("H e l l o")

Output

Hello
 Hello
H e l l o

Those are three different strings. A space is a character like any other.

The empty string

A string can have no characters at all. Write two quotes with nothing between them:

nothing = ""
print(nothing)
print(type(nothing))

Output

<class 'str'>

The first print shows an empty line. The empty string is still a string, in the same way that an empty box is still a box. It is the "zero" of text: it is falsy (Chapter 5), and adding it to another string changes nothing. It is very useful as a starting value when you build up text piece by piece.

Practice 7.1

Multiple choice

What is the job of the quote marks around a string?

Choose one answer

Predict the output

What does it print?

empty = ""
space = " "
print(bool(empty), bool(space))
print(empty == space)

7.2 Single quotes and double quotes

You can write a string with single quotes or double quotes. Python does not care which, as long as the opening and closing quote are the same kind:

print('Python' == "Python")

Output

True

Why have both? So that you can put one kind inside the other without any tricks:

print("It's a lovely day")
print('She said "hello" and left')

Output

It's a lovely day
She said "hello" and left

In the first line the string is wrapped in double quotes, so the apostrophe inside is just a character. In the second it is wrapped in single quotes, so the double quotes inside are just characters.

Here is what goes wrong when you use the same kind inside and outside:

print('It's a lovely day')

Output

  File "quotes.py", line 1
    print('It's a lovely day')
                            ^
SyntaxError: unterminated string literal (detected at line 1)

Python reads 'It' as a complete string, then finds s a lovely day which is not valid code, then a third quote that opens a string which never ends. The message unterminated string literal means "a string was opened and never closed".

Quick check

Which of these are valid strings? "He said 'no'", '5', "half', ''

Show the answer

Answer: all except "half', which opens with a double quote and tries to close with a single one. '5' is a string containing the digit character 5, and '' is the empty string.

Practice 7.2

Fix the bug

This should print Leo's bike is red, but it does not run. Fix it.

The program prints the lines below. Your program must print exactly these lines.

Example run

Leo's bike is red

Multiple choice

Three of these lines run. Which one stops with a SyntaxError?

Choose one answer

7.3 Escape sequences

What if the text contains both kinds of quote? Or a line break? You cannot press Enter in the middle of an ordinary string. For these cases Python has escape sequences: a backslash \ followed by a character. The backslash says "the next character has a special meaning", or sometimes "the next character has no special meaning".

Escaping quotes

\' and \" put a quote inside a string without ending it:

print('It\'s a lovely day')
print("She said \"hello\" and left")
print("It's \"complicated\"")

Output

It's a lovely day
She said "hello" and left
It's "complicated"

The backslash itself is not printed. It is an instruction to Python, not part of the text.

New lines and tabs

\n means "new line". Wherever it appears, the output moves to the start of the next line:

print("First line\nSecond line\nThird line")

Output

First line
Second line
Third line

One print, three lines of output. \t means "tab": it jumps forward to the next tab stop, which is useful for lining things up in simple columns:

print("Name\tScore")
print("Maya\t91")
print("Leo\t78")

Output

Name	Score
Maya	91
Leo	78

The backslash itself

Since a backslash starts an escape, how do you print an actual backslash? Escape it with another one:

print("One backslash: \\")
print("C:\\Users\\Maya")

Output

One backslash: \
C:\Users\Maya

The escapes worth knowing

Escape Meaning Example Shows as
\n new line "up\ndown" two lines
\t tab "x\ty" x and y with a gap
\\ one backslash "C:\\temp" C:\temp
\' single quote 'it\'s' it's
\" double quote "say \"hi\"" say "hi"
\uXXXX the character with that hexadecimal code point "\u00e9" é
\N{name} the character with that official Unicode name "\N{BLACK STAR}" ★

The last two let you write any character, even one that is not on your keyboard:

print("caf\u00e9")
print("\N{BLACK STAR} \N{SNOWMAN} \N{GREEK SMALL LETTER PI}")

Output

café
★ ☃ π

You will learn what code points are in → Chapter 9.

An escape is one character

This surprises many people. In your code \n takes two keystrokes, but in the string it is a single character:

print(len("ab"))
print(len("a\nb"))
print(len("\\"))

Output

2
3
1

"a\nb" has three characters: a, a new-line character, and b. And "\\" is one backslash. What you type in the code and what ends up in the string are not the same thing. len counts what is in the string.

A backslash before the wrong letter

Not every letter makes an escape. \d, \p and \s, for example, mean nothing special. Python currently keeps both characters, but warns you, because it is almost always a mistake:

print("C:\data\photos")
SyntaxWarning: "\d" is an invalid escape sequence. Such sequences will not work in the future. Did you mean "\\d"? A raw string is also an option.

Take the warning seriously: a future version of Python will make this an error. Either double the backslashes, or use a raw string (section 7.5).

Quick check

How many lines does print("one\ntwo\n\nthree") show, and is any of them empty?

Show the answer

Answer: four lines: one, two, an empty line, and three. Two \n in a row end one line and then immediately end another, empty, one.

Practice 7.3

Predict the output

What does it print?

print("Mon\nTue")
print("C:\\data")
print("Leo said \"hi\"")

Fill in the blank

Fill in the escape sequence so that one print shows two lines.

print("ReadyGo")

The finished program prints:

Target

Ready
Go

7.4 Strings over several lines: triple quotes

For a longer piece of text, writing \n everywhere is hard to read. Start and end the string with three quotes, and you can press Enter inside it as often as you like:

message = """Dear customer,

Your order has been shipped.
It should arrive within 3 days.

Thank you!"""
print(message)

Output

Dear customer,

Your order has been shipped.
It should arrive within 3 days.

Thank you!

Every line break you type becomes a \n in the string. Triple single quotes (''') work the same way, but triple double quotes are the usual choice.

A triple-quoted string is an ordinary str. Only the way of writing it is different. Both kinds of quote can appear inside without escaping:

print("""It's what she called "the plan".""")

Output

It's what she called "the plan".

Watch the edges

A triple-quoted string keeps everything between the quotes, including a line break right after the opening quotes and any spaces you use to indent:

text = """
    Indented line
"""
print(len(text))
print(text)

Output

19

    Indented line

The string starts with a new line, then four spaces, then the words, then another new line: 19 characters, not 13. If you do not want the first line break, start the text immediately after the opening quotes, as in the letter above, or put a backslash right after them. A backslash at the very end of a line means "pretend this line break is not here":

text = """\
Line one
Line two"""
print(text)

Output

Line one
Line two

Practice 7.4

Predict the output

What does it print?

text = """one
two"""
print(len(text))
print(text)

Multiple choice

How many characters does this string have?

text = """
Hi
"""
print(len(text))
Choose one answer

7.5 Raw strings

Windows file paths are full of backslashes, and that is a trap:

print("C:\new_folder\table.txt")

Output

C:
ew_folder	able.txt

Python saw \n and \t inside the path and did what it always does: a new line and a tab. The path is ruined.

One fix is to double every backslash: "C:\\new_folder\\table.txt". A neater fix is a raw string. Put the letter r immediately before the opening quote, and backslashes lose their special meaning:

print(r"C:\new_folder\table.txt")

Output

C:\new_folder\table.txt

In a raw string, what you see is what you get. Each backslash is just a backslash:

print(len("\n"))
print(len(r"\n"))

Output

1
2

"\n" is one new-line character. r"\n" is two characters: a backslash and the letter n.

Raw strings matter in two places: Windows paths, and regular expressions, a mini-language for searching text that uses backslashes heavily → Chapter 57.

The four ways to write a string

Form Example Use it when
Double quotes "It's here" the everyday choice
Single quotes 'Say "hi"' the text contains double quotes
Triple quotes """Line 1 ⏎ Line 2""" the text runs over several lines
Raw r"C:\new" the text contains backslashes that must stay as they are

All four make the same type of value. Once the string exists, Python has no idea, and no need to know, which form you used.

Practice 7.5

Predict the output

What does it print?

print(len("\t"), len(r"\t"))
print(r"one\ntwo")
print("C:\\temp" == r"C:\temp")

7.6 Measuring a string: len()

len is a built-in function that gives the length of a string: the number of characters in it.

print(len("Python"))
print(len("Hello, World!"))
print(len(""))
print(len(" "))

Output

6
13
0
1

Spaces and punctuation count: "Hello, World!" is ten letters, a comma, a space and an exclamation mark. The empty string has length 0.

len counts characters, not letters, and not keystrokes:

print(len("3.14"))
print(len("naïve"))
print(len("日本語"))
print(len("👋"))

Output

4
5
3
1

len only works on things that have a length. A number does not:

print(len(12345))

Output

Traceback (most recent call last):
  File "length.py", line 1, in <module>
    print(len(12345))
          ~~~^^^^^^^
TypeError: object of type 'int' has no len()

To count the digits of a number, convert it to text first, as in Chapter 6: len(str(12345)) is 5.

Quick check

What is len("Hi\tthere\n")?

Show the answer

Answer: 9. Hi is 2, the tab is 1, there is 5, and the new line is 1.

Practice 7.6

Fill in the blank

Fill in the blank so that the program counts the characters of the word.

word = input("Word: ")
print("Characters:", (word))

With the reply window, the finished program prints:

Target

Characters: 6

7.7 Joining strings: +

You saw in Chapter 4 that + joins two strings end to end. The proper name is concatenation, which simply means "chaining together":

first = "Maya"
last = "Tanaka"
print(first + last)
print(first + " " + last)

Output

MayaTanaka
Maya Tanaka

+ adds nothing of its own. If you want a space between the pieces, you must put one there yourself.

Both sides must be strings. For anything else, convert with str() first (Chapter 6):

items = 3
print("You have " + str(items) + " items")

Output

You have 3 items

Strings side by side

Two string literals written next to each other, with nothing between them, are joined automatically:

print("Hello, " "World")

Output

Hello, World

This is handy for breaking a long string across lines. Inside brackets, Python lets a line continue, so you can write:

message = ("This sentence is too long to fit comfortably "
           "on one line of code, so it is written in pieces "
           "that Python glues together.")
print(message)

Output

This sentence is too long to fit comfortably on one line of code, so it is written in pieces that Python glues together.

Notice the space at the end of each piece: without it the words would run together. This only works with literals written directly in the code. To join variables you still need +.

Practice 7.7

Fix the bug

For the replies Maya and Tanaka, this should print Welcome, Maya Tanaka!. The spaces are missing. Fix the last line.

With the replies Maya then Tanaka, the program prints the lines below. Your program must print exactly these lines.

Example run

Welcome, Maya Tanaka!

7.8 Repeating strings: *

A string times a whole number gives the string repeated that many times:

print("ha" * 3)
print("-" * 30)
print("=+" * 10)

Output

hahaha
------------------------------
=+=+=+=+=+=+=+=+=+=+

The order does not matter (3 * "ha" is the same), and multiplying by zero or a negative number gives the empty string:

print(3 * "ha")
print("ha" * 0 == "")
print("ha" * -2 == "")

Output

hahaha
True
True

Repetition is perfect for drawing lines and boxes that fit the text exactly, by combining it with len:

title = "Monthly Report"
print(title)
print("=" * len(title))

Output

Monthly Report
==============

Change the title and the underline changes with it. * is done before +, as with numbers, so "ab" + "c" * 3 is "abccc".

Practice 7.8

Put the lines in order

Put the lines in order. The program asks for a word and prints it inside a frame of stars that fits the word.

With the reply Lima, the program in the right order prints:

Target

********
* Lima *
********
  1. width = len(word) + 4
  2. print("*" * width)
  3. word = input("Word: ")
  4. print("* " + word + " *")
  5. print("*" * width)

Predict the output

What does it print?

print("no" * 2 + "!")
print(2 * "=-" + "=")
print("[" + "ha" * 0 + "]")

Write code

Progress bar. Ask for a whole number from 0 to 10: the number of steps that are done. Print one line: [, then one # for each step that is done, then one . for each step that is left, then ]. The part between the square brackets is always 10 characters long.

With the reply 3, the program prints the lines below. Your program must print exactly these lines.

Example run

[###.......]

7.9 Comparing and searching, briefly

Everything Chapter 5 said about comparisons works on strings:

print("cat" == "cat", "cat" == "Cat")
print("ant" < "bee")
print("thon" in "Python")
print("x" not in "Python")

Output

True False
True
True
True

== needs every character to match exactly. < and > use dictionary order by code point, so capitals come before lowercase letters. in asks whether one string appears somewhere inside another. A string found inside a bigger string is called a substring: "thon" is a substring of "Python". The empty string is a substring of every string, so "" in "Python" is True.

Practice 7.9

Predict the output

What does it print?

print("sun" in "sunny", "Sun" in "sunny")
print("kiwi" < "lemon", "Zebra" < "bee")
print("" in "Python")

7.10 A first look at f-strings

Building a sentence with + and str() works, but it is fiddly:

name = "Leo"
age = 30
print("My name is " + name + " and I am " + str(age) + " years old.")

Output

My name is Leo and I am 30 years old.

Count the quotes, plus signs and spaces you have to get right. Python has a much better tool: the f-string, short for formatted string. Put the letter f immediately before the opening quote. Then, inside the string, anything in curly brackets { } is replaced by its value:

name = "Leo"
age = 30
print(f"My name is {name} and I am {age} years old.")

Output

My name is Leo and I am 30 years old.

Same result, and you can read the sentence the way it will appear. No +, no str(): the f-string converts each value to text for you.

The curly brackets can hold any expression, not just a name:

price = 4.5
quantity = 3
print(f"Total: {price * quantity} dollars")
print(f"Next year you will be {30 + 1}.")
print(f"Your name has {len('Leo')} letters.")

Output

Total: 13.5 dollars
Next year you will be 31.
Your name has 3 letters.

Three things to remember:

  • Without the f, nothing happens. "Hello, {name}" is an ordinary string and prints the curly brackets as they are.
  • An f-string is still a string. You can store it, measure it and join it like any other: greeting = f"Hello, {name}!".
  • To show a real curly bracket, double it: f"{{name}} becomes {name}" gives {name} becomes Leo.
name = "Leo"
print("Hello, {name}")
print(f"Hello, {name}")
print(f"{{name}} becomes {name}")

Output

Hello, {name}
Hello, Leo
{name} becomes Leo

F-strings can also control decimal places, widths and alignment, which is how neat tables and receipts are printed. That has a whole chapter of its own → Chapter 16. From here on, this book uses simple f-strings whenever they make an example easier to read.

Quick check

With city = "Tokyo", what do f"{city}!", "{city}!" and f"{len(city) * 2}" give?

Show the answer

Answer: Tokyo!, then {city}! (no f, so no replacement), then 10 as a string: the length 5 times 2.

Practice 7.10

Fill in the blank

Fill in the expression so that the f-string shows the cost of all the tickets.

price = 2.5
tickets = 4
print(f"Total: {} dollars")

The finished program prints:

Target

Total: 10.0 dollars

Predict the output

What does it print?

city = "Lima"
print(f"{city} has {len(city)} letters")
print("{city}" + f"{city}")
print(f"{{city}} {city * 2}")

Put the lines in order

Put the lines in order. The program asks for the item first and for the number of items second. Each item costs 2 dollars.

With the replies pen then 3, the program in the right order prints:

Target

3 x pen costs 6 dollars
  1. count = int(input("How many: "))
  2. print(f"{count} x {item} costs {total} dollars")
  3. total = count * 2
  4. item = input("Item: ")

Fix the bug

For the replies Maya and 5, this should print Maya has 15 points: the program adds 10 bonus points. It prints the curly brackets instead. Fix it.

With the replies Maya then 5, the program prints the lines below. Your program must print exactly these lines.

Example run

Maya has 15 points

Write code

Receipt line. Ask three questions in this order: the name of an item, the price of one item (can be a decimal number), and the quantity (a whole number). Print one line in exactly this form: QUANTITY x ITEM = TOTAL dollars, where the total is the price times the quantity. Use an f-string.

With the replies Pen then 1.5 then 3, the program prints the lines below. Your program must print exactly these lines.

Example run

3 x Pen = 4.5 dollars

7.11 Strings cannot be changed

Strings are immutable. That is a formal word meaning "cannot be changed". Once a string exists, its characters are fixed forever. Every operation that seems to change a string actually builds a new string and leaves the old one exactly as it was.

word = "cat"
plural = word + "s"
print(word)
print(plural)

Output

cat
cats

word + "s" did not add an s to "cat". It made a brand-new string "cats", and word still refers to the original.

"But I can change a string variable!" you might say:

word = "cat"
word = word + "s"
print(word)

Output

cats

Look carefully at what happened, using the label picture from Chapter 3. The string "cat" was not altered. Python built the new string "cats", and then the label word was moved from the old string to the new one. id() shows that these are two different objects:

word = "cat"
before = id(word)
word = word + "s"
print(before == id(word))

Output

False
Before:   word ───► "cat"

After:              "cat"      (unchanged; thrown away if no label is left)
          word ───► "cats"     (a new string)

The difference between changing a value and moving a label to a new value seems like a small detail now. It becomes very important when you meet lists, which can be changed → Chapter 26. The next chapter shows what happens if you try to change one character of a string directly.

Practice 7.11

Multiple choice

A program runs word = "cat" and then word = word + "s". What happens on the second line?

Choose one answer

Put the lines in order

Put the lines in order so that the program runs and prints the target.

The program in the right order prints:

Target

rainbows rainbow
  1. print(word, longer)
  2. longer = word + "bow"
  3. word = "rain"
  4. word = longer + "s"

Fix the bug

This should print the word with s! at its end, for example cats! for the reply cat. It prints the word with no change. Fix it.

With the reply cat, the program prints the lines below. Your program must print exactly these lines.

Example run

cats!

7.12 Two ways to show a value: str() and repr()

Have you noticed that the shell shows strings with quotes, but print does not?

>>> "Python"
'Python'
>>> print("Python")
Python

Python has two text forms for every value:

  • The friendly form, for people reading the output. print and str() use it.
  • The exact form, for programmers. The shell uses it, and you can ask for it with the built-in repr() (short for representation). It looks like the code you would type to make that value.

For numbers the two are the same. For strings they differ, and the exact form reveals things you cannot otherwise see:

text = "Hi\tthere\n"
print(text)
print(repr(text))

Output

Hi	there

'Hi\tthere\n'

The first print performs the tab and the new line. The second shows the string as written in code, with quotes around it and the escapes visible.

This makes repr() one of the most useful debugging tools you will ever have. Invisible characters are a classic cause of bugs:

reply = "yes "
print(reply == "yes")
print(reply)
print(repr(reply))

Output

False
yes
'yes '

Printed normally, reply looks exactly like yes, and the False is a mystery. With repr, the extra space is plain to see. Whenever a string comparison fails and you cannot see why, print the repr of both sides.

Practice 7.12

Fill in the blank

The reply has a hidden space at its end. Fill in the function that shows the string in its exact form, with quotes.

reply = "yes "
print((reply))

The finished program prints:

Target

'yes '

7.13 Common mistakes

The mistake What you see The fix
Mismatched quotes: "hello' SyntaxError: unterminated string literal Open and close with the same kind
An apostrophe inside single quotes: 'it's' SyntaxError Use double quotes outside, or \'
Pressing Enter inside an ordinary string SyntaxError: unterminated string literal Use \n, or triple quotes
A Windows path in a normal string: "C:\new" A line break in the middle of the path Raw string r"C:\new", or forward slashes
"Age: " + 30 TypeError: can only concatenate str "Age: " + str(30) or f"Age: {30}"
Forgetting the f: "Hello, {name}" The curly brackets are printed Add the f before the quote
Forgetting spaces when joining MayaTanaka Add " " between the pieces
len(12345) TypeError: object of type 'int' has no len() len(str(12345))
Expecting word + "s" to change word word is unchanged Store the result: word = word + "s"

7.14 Putting it together

Practice 7.14

Write code

Menu line. Ask for the name of an item, then for its price. Keep the price as text, exactly as it was typed. Print one line that is exactly 20 characters wide: the item, then dots, then the price. The dots fill all the space between them. The item and the price together are always shorter than 20 characters.

With the replies Tea then 2.50, the program prints the lines below. Your program must print exactly these lines.

Example run

Tea.............2.50

7.15 How Python stores strings

Practice 7.15

Multiple choice

Why is len() instant, even for a string with a million characters?

Choose one answer

+ 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

What is the difference between "" and " "? Give the length and the truthiness of each.

Show the answer

"" is the empty string: length 0, falsy. " " contains one space character: length 1, truthy.

Check yourself

Why does Python allow both single and double quotes?

Show the answer

So that a string can contain one kind of quote without escaping it, by using the other kind as the delimiter.

Check yourself

How many characters are in the string "a\tb\\c"? List them.

Show the answer

Five: a, a tab, b, one backslash, c.

Check yourself

What does \n do inside a string? How is r"\n" different?

Show the answer

\n is a single new-line character: the output continues on the next line. r"\n" is a raw string with two characters, a backslash and an n, and prints as \n.

Check yourself

Why does print("C:\table") not show C:\table? Give two ways to fix it.

Show the answer

\t is the escape for a tab, so the output is C: followed by a tab and able. Fix it with "C:\\table" or r"C:\table".

Check yourself

What is the difference between "5" + "5", "5" * 5 and 5 * 5?

Show the answer

"5" + "5" joins two strings and gives "55". "5" * 5 repeats a string and gives "55555". 5 * 5 is arithmetic and gives the integer 25.

Check yourself

What does immutable mean? After s = "hi" and s = s + "!", has the string "hi" changed?

Show the answer

It cannot be changed after it is created. No: "hi" is untouched. A new string "hi!" was built and the name s was moved to it.

Check yourself

What does the f in front of a string do? What does "{x}" print without it?

Show the answer

It makes an f-string: each {expression} inside is replaced by its value. Without the f, "{x}" is ordinary text and prints {x}.

Check yourself

Why does the shell show 'hello' with quotes while print("hello") shows hello?

Show the answer

The shell shows the exact form (repr), which looks like code and includes quotes. print shows the friendly form, without quotes.

Check yourself

When is a triple-quoted string a better choice than \n?

Show the answer

When the text has several lines and you want the code to look like the output, for example a letter, a menu or a block of instructions.

Predict the output

Predict the output

print("one\ttwo\nthree")
print('It\'s "fine"')
print(r"one\ttwo\nthree")
Show the book's answer

In the raw string, the backslashes are ordinary characters.

print("one\ttwo\nthree")
print('It\'s "fine"')
print(r"one\ttwo\nthree")

Output

one	two
three
It's "fine"
one\ttwo\nthree

Predict the output

print(len("Hello World"), len("Hello\nWorld"), len(r"Hello\nWorld"))
print(len("") + len(" ") + len("  "))

Predict the output

print("ab" + "cd" * 2)
print(("ab" + "cd") * 2)
print("-" * 3 + ">" + " " * 2 + "|")

Predict the output

item = "pen"
count = 4
print(f"{count} {item}s cost {count * 1.5} dollars")
print("{count} {item}s")
print(f"{item * 2}{count + 1}")

Predict the output

text = "go"
other = text
text = text + "al"
print(text, other)

Fix the bug

Fix the bug

This should print Don't panic! but it does not run.

The program prints the lines below. Your program must print exactly these lines.

Example run

Don't panic!

Fix the bug

This should print the path C:\numbers\today.txt.

The program prints the lines below. Your program must print exactly these lines.

Example run

C:\numbers\today.txt

Fix the bug

This should print Maya has 3 messages. It prints {name} has {count} messages.

The program prints the lines below. Your program must print exactly these lines.

Example run

Maya has 3 messages

Fix the bug

This should print a title with a line of = under it that is exactly as long as the title. It crashes.

The program prints the lines below. Your program must print exactly these lines.

Example run

Results
=======

Fix the bug

This should print Total: 12 dollars. It crashes.

The program prints the lines below. Your program must print exactly these lines.

Example run

Total: 12 dollars

Coding problems

Write code · Easy

Three lines, one print. Using a single print and escape sequences, show your name, your city and your country on three separate lines.

This one is not checked automatically. Run your program, then compare it with the book's answer.

Show the book's answer
print("Maya Tanaka\nTokyo\nJapan")

Output

Maya Tanaka
Tokyo
Japan

Write code · Easy

Underlined heading. Ask for a heading and print it with a row of - above and below, both exactly as long as the heading.

Print three lines: the row of -, then the heading, then the row of - once more.

With the reply Chapter Seven, the program prints the lines below. Your program must print exactly these lines.

Example run

-------------
Chapter Seven
-------------

Write code · Easy

Introduce yourself. Store a name, an age and a hobby in variables and print one sentence that uses all three, with an f-string.

This one is not checked automatically. Run your program, then compare it with the book's answer.

Show the book's answer
name = "Leo"
age = 27
hobby = "chess"
print(f"My name is {name}, I am {age} years old, and I enjoy {hobby}.")

Output

My name is Leo, I am 27 years old, and I enjoy chess.

Write code · Medium

A quote within a quote. Print exactly this line, including both kinds of quote and the backslash: She said, "It's in C:\temp", and smiled. Do it in two different ways.

Print the line two times: one time for each of your two ways.

The program prints the lines below. Your program must print exactly these lines.

Example run

She said, "It's in C:\temp", and smiled.
She said, "It's in C:\temp", and smiled.

Write code · Medium

Simple table. Print a three-row table of items and prices with a header, using \t to line up the columns.

This one is not checked automatically. Run your program, then compare it with the book's answer.

Show the book's answer
print("Item\tPrice")
print("Pen\t1.50")
print("Book\t12.00")
print("Bag\t24.99")

Output

Item	Price
Pen	1.50
Book	12.00
Bag	24.99

Tabs only line up when every entry in the first column is shorter than one tab stop (usually 8 characters). Proper column formatting uses f-string widths → Chapter 16.

Write code · Medium

Triangle of stars. Using only print and * on strings, print a triangle five lines high: one star on the first line, two on the second, and so on.

The program prints the lines below. Your program must print exactly these lines.

Example run

*
**
***
****
*****

Write code · Hard

Centred title. Ask for a title and print it centred in a line 40 characters wide, with dots filling the space on both sides, for example .............Python Basics............... If the leftover space is odd, put the extra dot on the right.

Print one line that is exactly 40 characters wide. The title is always shorter than 40 characters.

With the reply Python Basics, the program prints the lines below. Your program must print exactly these lines.

Example run

.............Python Basics..............

Write code · Hard

Speech bubble. Ask for a short message and print it inside a box of the right size, with a \ and / style tail underneath. The top and bottom borders must fit any message length.

Use the shape of the example run: a top row of _ and a bottom row of -, both two characters longer than the message and both after one space, the message between < and >, and a tail of two backslashes after four and five spaces.

With the reply Strings are fun, the program prints the lines below. Your program must print exactly these lines.

Example run

 _________________
< Strings are fun >
 -----------------
    \
     \

Write code · Hard

Count without counting. Without running it, work out the length of "a\\b" + r"\n" + "\n" * 2 + f"{3 * 3}". Then check with len.

First work the length out on paper. Then print it with len.

The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

8

Chapter project: Reading chart

Project

Draw a small bar chart with text. Write a program that asks four questions, in this order:

  1. a name
  2. the number of books read in month 1 (a whole number)
  3. the number of books read in month 2 (a whole number)
  4. the number of books read in month 3 (a whole number)

Then print six lines, exactly in this form:

  • the heading Reading chart for NAME
  • a row of = that is exactly as long as the heading
  • Month 1 | then one # for each book, then one space, then the number
  • the same kind of line for Month 2 and for Month 3
  • Total: NUMBER books, with the sum of the three numbers

Build the heading with an f-string and store it in a variable, so that you can print it and also measure it.

With the replies Maya then 4 then 2 then 7, the program prints the lines below. Your program must print exactly these lines.

Example run

Reading chart for Maya
======================
Month 1 | #### 4
Month 2 | ## 2
Month 3 | ####### 7
Total: 13 books