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)
$ python string_basics.py
6
P y n
n o
Python!!!
"!" * 3 repeats a string, as in Chapter 15."Python": indices 0 to 5 from the start (below), to 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"
$ 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]
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)
$ python rebuild.py
Jami
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 up to index , but without . Without , the slice starts at the beginning; without , 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])
"keyboard". code/grade-7/03-strings/listings/slices.py$ python slices.py
key
board
key board
board
draobyek
[a:b] takes what lies between the marks and .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)
$ python vowels.py
vowels: 18
Onceuponatime,afoxlivedinaquietwood.
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
$ python methods.py
Hello, World!
HELLO, WORLD!
hello, world!
9
Hello, Noor!
3
Hello, World!
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))
$ python words.py
['the', 'fox', 'and', 'the', 'hen', 'and', 'the', 'dog']
8 words
3 times the
the-fox-and-the-hen-and-the-dog
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.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"))
$ python codes.py
65 97 48 32
HI
G
'
G G
233 122
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))
$ python palindrome.py
level True
Kayak True
Never odd or even True
Python False
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))
$ python passage_stats.py
characters: 124
letters: 94
words: 25
a 7
e 16
i 1
o 10
u 0
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"])?
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(" "))
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.
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"))
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"))
True. code/grade-7/03-strings/exercises/palindrome_fixed.pyExercise 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"))
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)
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?
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"))
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 , and s[k:] those with indices to the end: each index is in exactly one of the two slices, in order, so gluing them gives s. With the first slice is empty, and with 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)
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.
- Write 02-02-2020 and 12-02-2021 as eight digits, and check that both are palindromes.
- For a year from 2001 to 2099, written , the date must be followed by the year. What does that say about the month of every palindrome date of this century?
- 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)))
- Explain how
twowrites 7 as"07"and 12 as"12". - Why does
date_stringnot calltwofor the year? - Which chapter’s rule does
days_in_monthuse, and why does February need it? - Run
dates.py. Does it agree with question 1? - 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
forloops.)
Part III — The list.
- How many palindrome dates are there from 2001 to 2099? Which are the first and the last?
- Why is there exactly one palindrome date in some years, and none in others? Which years have one?
- Why is the last one so special?
- 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 reversed is : the month is always 02, February, and the day is , 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
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]))
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
10. A year has one palindrome date when the day exists in February, and none otherwise: there is only one possible month and day for each year. The day exists when is 0 (and is not 0), when is 1, or when is 2 and 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: 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.