---
title: "Strings"
book: "Primary & Middle School Computer Science"
subject: computer-science
language: en
chapter: 21
exercises: 12
source: https://one-course.com/books/computer-science/1/en/chapter/21-strings
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 21 — Strings

Sami’s favourite story is a few pages long, and he wonders which vowel it uses most. Counting by hand, with a pencil and five tally marks, he loses his place twice on the first page. For a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program), a text is a row of letters, much like a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of numbers, and walking through it is something we already know how to do.

**You already know.**

Every [character](#def-g7-strings-string) has a number, its code, in a [code table](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#def-g5-text-pictures-sound-as-numbers-code), and text is stored as those numbers ([Chapter 12](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#ch-g5-text-pictures-sound-as-numbers)). A [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) has indices from 0, a length given by `len`, and can be walked through with `for` ([Chapter 20](https://one-course.com/books/computer-science/1/en/chapter/20-lists#ch-g7-lists)).

## 21.1 A string is a sequence of characters

**Definition 21.1 (String and character).**

A *string* is a [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) made of characters in order: a text, written between quotes. A *character* is one letter, digit, space or sign. Strings have the type `str`.

A [string](#def-g7-strings-string) works like a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of [characters](#def-g7-strings-string): the same indices from 0, negative indices from the end, and `len` for its length.

```python
word = "Python"
print(len(word))
print(word[0], word[1], word[5])
print(word[-1], word[-2])
print(word + "!" * 3)
```

***Listing 21.1.** Indices and length of a [string](#def-g7-strings-string). code/grade-7/03-strings/listings/string_basics.py*

```
$ python string_basics.py
6
P y n
n o
Python!!!
```

***Output 21.1.** `"!" * 3` repeats a [string](#def-g7-strings-string), as in [Chapter 15](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#ch-g6-variables-and-input).*

![The string "Python": indices 0 to 5 from the start (below), -1 to -6 from the end (above).](https://one-course.com/images/onecourse/chapters/computer-science-1/g7-strings/fig-7c3b81df9629.svg)

*The [string](#def-g7-strings-string) `"Python"`: indices 0 to 5 from the start (below), $-1$ to $-6$ from the end (above).*

Unlike a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), a [string](#def-g7-strings-string) cannot be changed once it is made: Python refuses to replace one of its [characters](#def-g7-strings-string).

```python
name = "Sami"
name[0] = "J"
```

***Listing 21.2.** Changing a [character](#def-g7-strings-string)? code/grade-7/03-strings/listings/immutable.py*

```
$ python immutable.py
Traceback (most recent call last):
  File "~/session/immutable.py", line 2, in <module>
    name[0] = "J"
    ~~~~^^^
TypeError: 'str' object does not support item assignment
[exit status 1]
```

***Output 21.2.** A [string](#def-g7-strings-string) does not support [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) [assignment](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-assignment).*

Instead, we build a new [string](#def-g7-strings-string) and give it the old name:

```python
name = "Sami"
name = "J" + name[1:]     # a new string, made from a slice
print(name)
```

***Listing 21.3.** A new [string](#def-g7-strings-string) in place of the old one. code/grade-7/03-strings/listings/rebuild.py*

```
$ python rebuild.py
Jami
```

***Output 21.3.** `name[1:]` is “everything from [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) 1 on”.*

## 21.2 Slices

**Definition 21.2 (Slice).**

A *slice* is a part of a [string](#def-g7-strings-string) (or of a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list)) taken by indices: `s[a:b]` holds the [characters](#def-g7-strings-string) from [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) $a$ up to [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) $b$, but without $b$. Without $a$, the slice starts at the beginning; without $b$, it goes to the end; `s[::-1]` walks backwards and gives the [string](#def-g7-strings-string) reversed.

```python
word = "keyboard"
print(word[0:3])
print(word[3:8])
print(word[:3], word[3:])
print(word[-5:])
print(word[::-1])
```

***Listing 21.4.** [Slices](#def-g7-strings-slice) of `"keyboard"`. code/grade-7/03-strings/listings/slices.py*

```
$ python slices.py
key
board
key board
board
draobyek
```

***Output 21.4.** A [slice](#def-g7-strings-slice) never includes its end [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list).*

![Think of the indices as standing between the characters: the slice (a:b) takes what lies between the marks a and b.](https://one-course.com/images/onecourse/chapters/computer-science-1/g7-strings/fig-204103fa86b1.svg)

*Think of the indices as standing *between* the [characters](#def-g7-strings-string): the [slice](#def-g7-strings-slice) `[a:b]` takes what lies between the marks $a$ and $b$.*

## 21.3 Walking through text

`for ch in s:` visits the [characters](#def-g7-strings-string) one by one. Counting vowels is a walk with a [counter](https://one-course.com/books/computer-science/1/en/chapter/18-repeating-with-while#def-g6-while-loops-counter); building a new [string](#def-g7-strings-string) is a walk that adds [characters](#def-g7-strings-string) to a [string](#def-g7-strings-string) that starts empty, `""`. The test `ch in "aeiouAEIOU"` is true when the [character](#def-g7-strings-string) is one of those ten.

```python
text = "Once upon a time, a fox lived in a quiet wood."
vowels = 0
for ch in text:
    if ch in "aeiouAEIOU":
        vowels = vowels + 1
print("vowels:", vowels)

no_spaces = ""
for ch in text:
    if ch != " ":
        no_spaces = no_spaces + ch
print(no_spaces)
```

***Listing 21.5.** Counting vowels and removing spaces. code/grade-7/03-strings/listings/vowels.py*

```
$ python vowels.py
vowels: 18
Onceuponatime,afoxlivedinaquietwood.
```

***Output 21.5.** 18 vowels, and the text without its spaces.*

## 21.4 Useful string methods

**Definition 21.3 (String method).**

A *string method* is a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) that belongs to [strings](#def-g7-strings-string) and is called after a [string](#def-g7-strings-string) and a point, as in `s.upper()`. A [string](#def-g7-strings-string) method never changes the [string](#def-g7-strings-string): it returns a new [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value).

```python
s = "  Hello, World!  "
print(s.strip())
print(s.upper())
print(s.lower())
print(s.find("World"))
print(s.replace("World", "Noor"))
print(s.count("l"))
print(s)                  # s itself has not changed
```

***Listing 21.6.** A few [string methods](#def-g7-strings-string-method). code/grade-7/03-strings/listings/methods.py*

```
$ python methods.py
Hello, World!
  HELLO, WORLD!  
  hello, world!  
9
  Hello, Noor!  
3
  Hello, World!
```

***Output 21.6.** `strip` removes the spaces at both ends; `find` gives the [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) where `"World"` starts; the last line shows that `s` is unchanged.*

Two methods turn a text into a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of words and back: `split` cuts a [string](#def-g7-strings-string) at each separator, and `join` glues the [strings](#def-g7-strings-string) of a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), with a separator between them. Without an argument, `split()` cuts at any run of spaces and line breaks.

```python
sentence = "the fox and the hen and the dog"
words = sentence.split(" ")
print(words)
print(len(words), "words")
print(words.count("the"), "times the")
print("-".join(words))
```

***Listing 21.7.** Cutting a sentence into words and gluing them back. code/grade-7/03-strings/listings/words.py*

```
$ python words.py
['the', 'fox', 'and', 'the', 'hen', 'and', 'the', 'dog']
8 words
3 times the
the-fox-and-the-hen-and-the-dog
```

***Output 21.7.** A [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) method, `count`, counts the [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) equal to `"the"`.*

![split cuts a string into a list of strings; join glues a list of strings into one string.](https://one-course.com/images/onecourse/chapters/computer-science-1/g7-strings/fig-cbbdfdac5401.svg)

*`split` cuts a [string](#def-g7-strings-string) into a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of [strings](#def-g7-strings-string); `join` glues a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of [strings](#def-g7-strings-string) into one [string](#def-g7-strings-string).*

## 21.5 The code of a character

`ord` gives the code of a [character](#def-g7-strings-string), and `chr` gives the [character](#def-g7-strings-string) of a code: Python uses the same codes as the table of [Chapter 12](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#ch-g5-text-pictures-sound-as-numbers) for the letters, digits and signs of English. Its table goes much further, and holds the [characters](#def-g7-strings-string) of every alphabet: `chr(1046)` is a Cyrillic capital letter, Arabic and Hindi [characters](#def-g7-strings-string) have codes in the thousands, and Chinese [characters](#def-g7-strings-string) in the tens of thousands. The next book explains how such codes are stored in [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte).

```python
print(ord("A"), ord("a"), ord("0"), ord(" "))
print(chr(72) + chr(73))
print(chr(ord("g") - 32))     # 32 places from a small letter to its capital
print(chr(ord("G") - 32))     # but a capital has no capital 32 places away
print("g".upper(), "G".upper())
print(ord("é"), ord("z"))
```

***Listing 21.8.** Codes and [characters](#def-g7-strings-string). code/grade-7/03-strings/listings/codes.py*

```
$ python codes.py
65 97 48 32
HI
G
'
G G
233 122
```

***Output 21.8.** The small letters come 32 places after the capitals.*

Subtracting 32 turns a small `g` into a capital, but a capital `G` becomes an apostrophe. `upper` knows which [characters](#def-g7-strings-string) have a capital and leaves the others alone: it is always the better choice.

A palindrome reads the same in both directions. The [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) below first puts the text in small letters and removes its spaces, then compares it with its reverse:

```python
def is_palindrome(s):
    s = s.lower().replace(" ", "")
    return s == s[::-1]


for text in ["level", "Kayak", "Never odd or even", "Python"]:
    print(text, is_palindrome(text))
```

***Listing 21.9.** A palindrome test. code/grade-7/03-strings/listings/palindrome.py*

```
$ python palindrome.py
level True
Kayak True
Never odd or even True
Python False
```

***Output 21.9.** Capitals and spaces do not count.*

Finally, a few counts on a short passage. A [string](#def-g7-strings-string) between triple quotes may run over several lines; `ch.isalpha()` is true when the [character](#def-g7-strings-string) is a letter.

```python
passage = """The fox looked at the hen, and the hen looked at the fox.
Neither of them moved. Then the farmer's dog barked, and both ran."""

letters = 0
for ch in passage:
    if ch.isalpha():
        letters = letters + 1
words = passage.split()
print("characters:", len(passage))
print("letters:", letters)
print("words:", len(words))

lower = passage.lower()
for letter in "aeiou":
    print(letter, lower.count(letter))
```

***Listing 21.10.** Counting [characters](#def-g7-strings-string), letters, words and vowels. code/grade-7/03-strings/listings/passage_stats.py*

```
$ python passage_stats.py
characters: 124
letters: 94
words: 25
a 7
e 16
i 1
o 10
u 0
```

***Output 21.10.** The line break counts as a [character](#def-g7-strings-string), too.*

![How often each letter appears in the passage of , capitals counted with small letters. A script of the chapter counts them from the listing itself.](https://one-course.com/images/onecourse/chapters/computer-science-1/g7-strings/fig-d246596b2ae3.svg)

*How often each letter appears in the passage of [Listing 21.10](#lst-g7-strings-passage), capitals counted with small letters. A script of the chapter counts them from the listing itself.*

## 21.6 Exercises

**Exercise 21.1 ★.**

With `s = "computer"`, what are `s[1:4]`, `s[-1]` and `s[::-1]`?

**Solution of Exercise 21.1.**

`s[1:4]` is `"omp"` (indices 1, 2, 3), `s[-1]` is `"r"` and `s[::-1]` is `"retupmoc"`.

**Exercise 21.2 ★.**

What does `"a,b,c".split(",")` give? And `" + ".join(["1", "2", "3"])`?

**Solution of Exercise 21.2.**

The [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) `["a", "b", "c"]`, and the [string](#def-g7-strings-string) `"1 + 2 + 3"`.

**Exercise 21.3 ★.**

What are `ord("C")` and `chr(100)`? Use the codes of [Output 21.8](#out-g7-strings-codes).

**Solution of Exercise 21.3.**

The capitals follow `A` (65) in order, so `ord("C")` is 67. The small letters follow `a` (97): 100 is `"d"`.

**Exercise 21.4 ★.**

Write a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that counts the spaces of a sentence by walking through it, and check the result with `count`.

**Solution of Exercise 21.4.**

```python
sentence = "A list holds many values in order."
spaces = 0
for ch in sentence:
    if ch == " ":
        spaces = spaces + 1
print(spaces, sentence.count(" "))
```

*Counting spaces. code/grade-7/03-strings/exercises/spaces.py*

It prints `6 6`: both ways agree.

**Exercise 21.5 ★★.**

Tom writes `s[len(s)]` to get the last [character](#def-g7-strings-string) of a [string](#def-g7-strings-string), and gets an `IndexError`. Why? Give two correct ways.

**Solution of Exercise 21.5.**

The indices of a [string](#def-g7-strings-string) of length $n$ go from 0 to $n - 1$, so [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) `len(s)` is past the end. The last [character](#def-g7-strings-string) is `s[len(s) - 1]`, or simply `s[-1]`.

**Exercise 21.6 ★★.**

This palindrome test says that `"Kayak"` is not a palindrome. Why? Fix it.

```python
def is_palindrome(s):
    return s.lower() == s[::-1]


print(is_palindrome("Kayak"))
```

***Listing 21.11.** A test that gets capitals wrong. code/grade-7/03-strings/exercises/palindrome_bug.py*

**Solution of Exercise 21.6.**

`s.lower()` is compared with `s[::-1]`, the reverse of the original [string](#def-g7-strings-string), which still has its capital: `"kayak"` against `"kayaK"`. Both sides must be in small letters; the simplest way is to change `s` first:

```python
def is_palindrome(s):
    s = s.lower()
    return s == s[::-1]


print(is_palindrome("Kayak"))
```

*Small letters on both sides: it prints `True`. code/grade-7/03-strings/exercises/palindrome_fixed.py*

**Exercise 21.7 ★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `initials(full_name)`: `"ada lovelace"` gives `"A.L."`.

**Solution of Exercise 21.7.**

```python
def initials(full_name):
    result = ""
    for word in full_name.split():
        result = result + word[0].upper() + "."
    return result


print(initials("ada lovelace"))
print(initials("Grace Brewster Hopper"))
```

*Initials. code/grade-7/03-strings/exercises/initials.py*

It prints `A.L.` and `G.B.H.`.

**Exercise 21.8 ★★.**

Write a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that prints a text with every vowel replaced by `*`.

**Solution of Exercise 21.8.**

```python
text = "Once upon a time"
starred = ""
for ch in text:
    if ch.lower() in "aeiou":
        starred = starred + "*"
    else:
        starred = starred + ch
print(starred)
```

*Hiding the vowels. code/grade-7/03-strings/exercises/star_vowels.py*

It prints `*nc* *p*n * t*m*`. (`text.replace` would need one call per vowel, capitals included.)

**Exercise 21.9 ★★.**

How many different [slices](#def-g7-strings-slice) `s[i:i + 3]` of length 3 does a [string](#def-g7-strings-string) of length 10 have?

**Solution of Exercise 21.9.**

The [slice](#def-g7-strings-slice) starts at [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) $i$ and ends before $i + 3$, so its last [character](#def-g7-strings-string) has [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) $i + 2$, at most 9: $i$ goes from 0 to 7, which makes 8 [slices](#def-g7-strings-slice).

**Exercise 21.10 ★★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `longest_word(sentence)` that returns the longest word of a sentence (the first one, if several are as long).

**Solution of Exercise 21.10.**

A best-so-far walk, comparing lengths:

```python
def longest_word(sentence):
    words = sentence.split()
    best = words[0]
    for word in words:
        if len(word) > len(best):
            best = word
    return best


print(longest_word("the quick brown fox jumps over the lazy dog"))
```

*The longest word. code/grade-7/03-strings/exercises/longest_word.py*

It prints `quick`: `brown` and `jumps` are as long, but come later, and only a strictly longer word replaces the best.

**Exercise 21.11 ★★★.**

Explain why `s[::-1][::-1]` is always `s`, and why `s[:k] + s[k:]` is `s` for every `k` from 0 to `len(s)`.

**Solution of Exercise 21.11.**

`s[::-1]` puts the last [character](#def-g7-strings-string) first, and so on; reversing again puts every [character](#def-g7-strings-string) back in its place. `s[:k]` holds the [characters](#def-g7-strings-string) with indices 0 to $k - 1$, and `s[k:]` those with indices $k$ to the end: each [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is in exactly one of the two [slices](#def-g7-strings-slice), in order, so gluing them gives `s`. With $k = 0$ the first [slice](#def-g7-strings-slice) is empty, and with $k = \texttt{len(s)}$ the second one is.

**Exercise 21.12 ★★★.**

In a mirror, a word written in small letters appears reversed, with `b` and `d` swapped, and `p` and `q` swapped. Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `mirror(word)` that returns what the mirror shows, using the two [strings](#def-g7-strings-string) `"bdpq"` and `"dbqp"`, and find which of `bid`, `bud`, `pod`, `pq` and `box` look the same in the mirror.

**Solution of Exercise 21.12.**

```python
def mirror(word):
    """Reverse the word, then swap b and d, p and q, as in a mirror."""
    result = ""
    for ch in word[::-1]:
        i = "bdpq".find(ch)
        if i >= 0:
            ch = "dbqp"[i]
        result = result + ch
    return result


for word in ["bid", "bud", "pod", "pq", "box"]:
    print(word, mirror(word), mirror(word) == word)
```

*A mirror test. code/grade-7/03-strings/exercises/mirror.py*

`bid`, `bud` and `pq` look the same in the mirror; `pod` becomes `boq`, and `box` becomes `xod`.

## 21.7 Problem: Palindrome Dates

**Problem 21.1.**

Weekend problem — dates that read both ways

Write a date with two digits for the day, two for the month and four for the year, without separators: the 2nd of February 2020 is `02022020`. Some dates read the same backwards: they are *palindrome dates*.

**Part I — By hand.**

1. Write 02-02-2020 and 12-02-2021 as eight digits, and check that both are palindromes.
2. For a year from 2001 to 2099, written $2\,0\,c\,d$ , the date must be $d\,c\,0\,2$ followed by the year. What does that say about the month of every palindrome date of this century?
3. For the year 2092, which day would it have to be? Does that day exist?

**Part II — Functions.**

```python
def two(n):
    """n as two digits: 7 gives "07", 12 gives "12"."""
    return ("0" + str(n))[-2:]


def date_string(day, month, year):
    return two(day) + two(month) + str(year)


def is_palindrome(s):
    return s == s[::-1]


def days_in_month(month, year):
    days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if month == 2 and year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
        return 29
    return days[month - 1]


if __name__ == "__main__":
    print(date_string(2, 2, 2020), is_palindrome(date_string(2, 2, 2020)))
    print(date_string(12, 2, 2021), is_palindrome(date_string(12, 2, 2021)))
```

***Listing 21.12.** Dates as [strings](#def-g7-strings-string) of eight digits. code/grade-7/03-strings/listings/dates.py*

4. Explain how `two` writes 7 as `"07"` and 12 as `"12"` .
5. Why does `date_string` not call `two` for the year?
6. Which chapter’s rule does `days_in_month` use, and why does February need it?
7. Run `dates.py` . Does it agree with question 1?
8. Write a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that walks through every day of every year from 2001 to 2099 and keeps the palindrome dates in a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) . (Use three nested `for` [loops](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) .)

**Part III — The list.**

9. How many palindrome dates are there from 2001 to 2099? Which are the first and the last?
10. Why is there exactly one palindrome date in some years, and none in others? Which years have one?
11. Why is the last one so special?
12. State the result.

**Solution of Problem 21.1.**

**1.** `02022020` and `12022021`: reading them from the right gives the same digits.

**2.** The year $2\,0\,c\,d$ reversed is $d\,c\,0\,2$: the month is always `02`, February, and the day is $d\,c$, the last two digits of the year in reverse order.

**3.** For 2092 the day is 29: the 29th of February 2092. It exists, since 2092 is divisible by 4 and is a leap year.

**4.** `"0" + str(n)` puts a 0 in front: `"07"` or `"012"`. The [slice](#def-g7-strings-slice) `[-2:]` keeps the last two [characters](#def-g7-strings-string): `"07"` and `"12"`.

**5.** The year already has four digits, for every year from 1000 to 9999.

**6.** The leap-year rule of [Chapter 17](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#ch-g6-if-else): February has 29 days in a leap year and 28 otherwise, and all the palindrome dates of this century are in February.

**7.** It agrees:

```
$ python dates.py
02022020 True
12022021 True
```

***Output 21.11.** The two dates of question 1.*

**8.** Three [nested loops](https://one-course.com/books/computer-science/1/en/chapter/16-repeating-with-for-turtle-drawings#def-g6-for-loops-turtle-nested) (year, month, day), each date turned into a [string](#def-g7-strings-string) and tested:

```python
from dates import date_string, days_in_month, is_palindrome

found = []
for year in range(2001, 2100):
    for month in range(1, 13):
        for day in range(1, days_in_month(month, year) + 1):
            s = date_string(day, month, year)
            if is_palindrome(s):
                found.append(s[0:2] + "-" + s[2:4] + "-" + s[4:])
print(len(found), "palindrome dates")
print("first:", found[0], " last:", found[-1])
for i in range(0, len(found), 5):
    print("  ".join(found[i:i + 5]))
```

*Every palindrome date of the century. code/grade-7/03-strings/listings/all_dates.py*

**9.** 29 dates, from 10 February 2001 to 29 February 2092:

```
$ python all_dates.py
29 palindrome dates
first: 10-02-2001  last: 29-02-2092
10-02-2001  20-02-2002  01-02-2010  11-02-2011  21-02-2012
02-02-2020  12-02-2021  22-02-2022  03-02-2030  13-02-2031
23-02-2032  04-02-2040  14-02-2041  24-02-2042  05-02-2050
15-02-2051  25-02-2052  06-02-2060  16-02-2061  26-02-2062
07-02-2070  17-02-2071  27-02-2072  08-02-2080  18-02-2081
28-02-2082  09-02-2090  19-02-2091  29-02-2092
```

***Output 21.12.** The palindrome dates from 2001 to 2099.*

**10.** A year $2\,0\,c\,d$ has one palindrome date when the day $d\,c$ exists in February, and none otherwise: there is only one possible month and day for each year. The day $d\,c$ exists when $d$ is 0 (and $c$ is not 0), when $d$ is 1, or when $d$ is 2 and $c$ is at most 8, or 9 in a leap year. So the years ending in 0 (except 2000), in 1, and in 2 up to 2082, plus 2092: $9 + 10 +
10 = 29$ years.

**11.** It is the only one that falls on the 29th of February, a day that exists only in leap years.

**12.** **Result.** There are 29 palindrome dates between 2001 and 2099, all in February, from 10-02-2001 to 29-02-2092.
