Computer Science · Book 1 · Grades 1–9

Primary & Middle School Computer Science

Primary & Middle School Computer Science · Grades 1–9

21Strings

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, a text is a row of letters, much like a list of numbers, and walking through it is something we already know how to do.

You already know

Every character has a number, its code, in a code table, and text is stored as those numbers (Chapter 12). A list has indices from 0, a length given by len, and can be walked through with for (Chapter 20).

21.1 A string is a sequence of characters

Definition 21.1 (String and character)

A string is a 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 works like a list of characters: the same indices from 0, negative indices from the end, and len for its length.

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. 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, as in Chapter 15.
The string "Python": indices 0 to 5 from the start (below), -1 to -6 from the end (above).
The string "Python": indices 0 to 5 from the start (below), −1-1 to −6-6 from the end (above).

Unlike a list, a string cannot be changed once it is made: Python refuses to replace one of its characters.

name = "Sami"
name[0] = "J"
Listing 21.2. Changing a character? 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 does not support item assignment.

Instead, we build a new string and give it the old name:

name = "Sami"
name = "J" + name[1:]     # a new string, made from a slice
print(name)
Listing 21.3. A new 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 1 on”.

21.2 Slices

Definition 21.2 (Slice)

A slice is a part of a string (or of a list) taken by indices: s[a:b] holds the characters from index aa up to index bb, but without bb. Without aa, the slice starts at the beginning; without bb, it goes to the end; s[::-1] walks backwards and gives the string reversed.

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 of "keyboard". code/grade-7/03-strings/listings/slices.py
$ python slices.py
key
board
key board
board
draobyek
Output 21.4. A slice never includes its end index.
Think of the indices as standing between the characters: the slice [a:b] takes what lies between the marks a and b.
Think of the indices as standing between the characters: the slice [a:b] takes what lies between the marks aa and bb.

21.3 Walking through text

for ch in s: visits the characters one by one. Counting vowels is a walk with a counter; building a new string is a walk that adds characters to a string that starts empty, "". The test ch in "aeiouAEIOU" is true when the character is one of those ten.

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 that belongs to strings and is called after a string and a point, as in s.upper(). A string method never changes the string: it returns a new value.

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. 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 where "World" starts; the last line shows that s is unchanged.

Two methods turn a text into a list of words and back: split cuts a string at each separator, and join glues the strings of a list, with a separator between them. Without an argument, split() cuts at any run of spaces and line breaks.

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 method, count, counts the items equal to "the".
split cuts a string into a list of strings; join glues a list of strings into one string.
split cuts a string into a list of strings; join glues a list of strings into one string.

21.5 The code of a character

ord gives the code of a character, and chr gives the character of a code: Python uses the same codes as the table of Chapter 12 for the letters, digits and signs of English. Its table goes much further, and holds the characters of every alphabet: chr(1046) is a Cyrillic capital letter, Arabic and Hindi characters have codes in the thousands, and Chinese characters in the tens of thousands. The next book explains how such codes are stored in bytes.

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. 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 have a capital and leaves the others alone: it is always the better choice.

A palindrome reads the same in both directions. The function below first puts the text in small letters and removes its spaces, then compares it with its reverse:

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 between triple quotes may run over several lines; ch.isalpha() is true when the character is a letter.

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, 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, 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.
How often each letter appears in the passage of Listing 21.10, 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

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

Solution of Exercise 21.2.

The list ["a", "b", "c"], and the string "1 + 2 + 3".

Exercise 21.3 ★

What are ord("C") and chr(100)? Use the codes of Output 21.8.

Solution

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 that counts the spaces of a sentence by walking through it, and check the result with count.

Solution

Solution of Exercise 21.4.

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 of a string, and gets an IndexError. Why? Give two correct ways.

Solution

Solution of Exercise 21.5.

The indices of a string of length nn go from 0 to n−1n - 1, so index len(s) is past the end. The last character 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.

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

Solution of Exercise 21.6.

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

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 initials(full_name): "ada lovelace" gives "A.L.".

Solution

Solution of Exercise 21.7.

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 that prints a text with every vowel replaced by *.

Solution

Solution of Exercise 21.8.

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 s[i:i + 3] of length 3 does a string of length 10 have?

Solution

Solution of Exercise 21.9.

The slice starts at index ii and ends before i+3i + 3, so its last character has index i+2i + 2, at most 9: ii goes from 0 to 7, which makes 8 slices.

Exercise 21.10 ★★★

Write a function longest_word(sentence) that returns the longest word of a sentence (the first one, if several are as long).

Solution

Solution of Exercise 21.10.

A best-so-far walk, comparing lengths:

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

Solution of Exercise 21.11.

s[::-1] puts the last character first, and so on; reversing again puts every character back in its place. s[:k] holds the characters with indices 0 to k−1k - 1, and s[k:] those with indices kk to the end: each index is in exactly one of the two slices, in order, so gluing them gives s. With k=0k = 0 the first slice is empty, and with k=len(s)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 mirror(word) that returns what the mirror shows, using the two strings "bdpq" and "dbqp", and find which of bid, bud, pod, pq and box look the same in the mirror.

Solution

Solution of Exercise 21.12.

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 d2\,0\,c\,d, the date must be d c 0 2d\,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.

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 of eight digits. code/grade-7/03-strings/listings/dates.py
  1. Explain how two writes 7 as "07" and 12 as "12".
  2. Why does date_string not call two for the year?
  3. Which chapter’s rule does days_in_month use, and why does February need it?
  4. Run dates.py. Does it agree with question 1?
  5. Write a program that walks through every day of every year from 2001 to 2099 and keeps the palindrome dates in a list. (Use three nested for loops.)

Part III — The list.

  1. How many palindrome dates are there from 2001 to 2099? Which are the first and the last?
  2. Why is there exactly one palindrome date in some years, and none in others? Which years have one?
  3. Why is the last one so special?
  4. State the result.
Solution

Solution of Problem 21.1.

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

2. The year 2 0 c d2\,0\,c\,d reversed is d c 0 2d\,c\,0\,2: the month is always 02, February, and the day is d cd\,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 [-2:] keeps the last two characters: "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: 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 (year, month, day), each date turned into a string and tested:

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 d2\,0\,c\,d has one palindrome date when the day d cd\,c exists in February, and none otherwise: there is only one possible month and day for each year. The day d cd\,c exists when dd is 0 (and cc is not 0), when dd is 1, or when dd is 2 and cc 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=299 + 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.

Terms defined in this chapter

See all 1050 terms in the glossary