8. Strings in Python
About this chapter
Big idea: A string is a row of characters. You can read any letter, join rows, and cut slices, but you cannot rewrite one letter in place.
This is an original lesson that follows the Class 11 Computer Science syllabus. Read the key words first. Cover a worked answer and try the steps yourself before you look. For a program, say what it will print before you read the real output.
- Create strings with single, double or triple quotes.
- Read one character with a positive or negative index.
- Explain why a string is immutable, and show the error.
- Join, repeat, test membership, and slice with start, stop and step.
- Walk through every character with a for loop or a while loop.
- Use common string methods and built-in functions with real output.
- Write small programs that count vowels, reverse text, and test a palindrome.
People have stored text as number codes for a long time. In the 1960s, ASCII used 7 bits per English character. That list was too small for other scripts. Unicode, begun in the 1990s, gives a number to each character in many writing systems. Python 3, first released in 2008, made every ordinary string a Unicode string, so the same type can hold letters, digits, spaces and symbols.
8.1 Strings
A string is a row of characters held as one value.
A string is a row of characters stored as one value.
A string is a sequence: an ordered row of items.
Each item is a character: a letter, digit, space, or symbol.
Python stores characters as UNICODE, a big list of numbers that name characters.
You type quotes around the text. You do not type those numbers.
Make a string by wrapping text in quotes.
Single quotes and double quotes both work. They make the same kind of value.
a = 'bus stop'
b = "bus stop"
print(a)
print(b)
print(a == b)
print(type(a).__name__)bus stop
bus stop
True
stra == b is True. The wrappers are not stored. The type name is str.
Triple quotes make a string that can cover more than one line.
Use three single quotes, or three double quotes.
The line break is part of the string.
notice = """bag on
the hook"""
print(notice)
print(len(notice))bag on
the hook
15One pair of quotes makes one string, even with three quote marks.
Python has no separate character type. One letter is still a string.
Its length is 1.
mark = "Q"
print(type(mark).__name__)
print(len(mark))str
1An empty string has quotes with nothing inside. Its length is 0. It is still a string.
>>> len("")
0
>>> "" == ""
TrueA string may hold digits and spaces. Those are characters too.
"204" is not the integer 204. It is three digit characters in a row.
You may still read each digit by index.
code = "204"
print(len(code))
print(code[0])
print(code[0] + code[1] + code[2])
print(type(code).__name__)3
2
204
strLength is 3. Joining the three digits still gives a string.
If you need a quote mark inside, wrap the string in the other kind of quote.
The wrapper is not stored. Only the inner characters are stored.
print("Student A's bag")
print('He said "go"')
print(len("Student A's bag"))Student A's bag
He said "go"
15- String: an ordered row of characters.
- Character: one letter, digit, space or symbol.
- UNICODE: a numbering system for characters.
- Empty string: a string with length 0.
Student A types the same words once in single quotes and once in double quotes. Are they different strings?
Goal. Decide if the two wrappers make two values.
Rule. Quotes wrap the text. They are not stored.
Check. Both hold the same characters in the same order.
Compare. == is True for matching characters.
Result: Result: no. Both wrappers make the same string value.
Cover the answers. Try each item on paper first.
8.2 Accessing characters in a string
Each character sits in a numbered slot called an index.
Indexing means picking one character by its place.
Write the string, then square brackets, then an integer. That integer is the index.
Counting from the left starts at 0, not 1.
If the string has characters, the last index from the left is .
For NOTEBOOK, , so the last left index is .
How to read the figure. Box T has 2 above and below. Both names point at T.
| Letter | From the left | From the right |
|---|---|---|
| N | 0 | -8 |
| O | 1 | -7 |
| T | 2 | -6 |
| E | 3 | -5 |
| B | 4 | -4 |
| O | 5 | -3 |
| O | 6 | -2 |
| K | 7 | -1 |
A negative index counts from the right. The last character is .
The first character is . For NOTEBOOK that name is .
word = "NOTEBOOK"
print(word[0])
print(word[3])
print(word[7])
print(word[-1])
print(word[-8])
print(word[2 + 4])N
E
K
K
N
Oword[0] is N. word[-1] is K. word[2 + 4] is the same as word[6] (letter O).
The built-in function len returns how many characters are in the string. Spaces count. So do punctuation marks.
print(len("NOTEBOOK"))
print(len("GAME DAY"))
label = "GAME DAY"
n = len(label)
print(label[n - 1])
print(label[-n])
print(label[4])8
8
Y
GGAME DAY has a space at index 4. Length counts it, so the length is 8, not 7.
| Index | Character in GAME DAY |
|---|---|
| 0 | G |
| 1 | A |
| 2 | M |
| 3 | E |
| 4 | a space |
| 5 | D |
| 6 | A |
| 7 | Y |
How to read the table. Row 4 is a space, not a missing letter.
An index that is too big or too small raises IndexError. A non-integer index raises TypeError.
The programs below catch the errors and print the error type.
word = "NOTEBOOK"
try:
print(word[15])
except IndexError as err:
print(type(err).__name__)
print(err)
try:
print(word[1.5])
except TypeError as err:
print(type(err).__name__)
print(err)IndexError
string index out of range
TypeError
string indices must be integers, not 'float'The last left index is length minus one, never the length.
- Index: the integer that names one place in the string.
- Indexing: reading a character by its index.
- Negative index: an index counted from the right, starting at -1.
- len: the built-in function that returns the length.
The string is NOTEBOOK. What character is at index 4, and what character is at index -3?
Goal. Read one left index and one right index.
Rule. Left counts from 0. Right counts from .
Left. 0 is N, 1 is O, 2 is T, 3 is E, 4 is B.
Right. is K, is O, is O.
Result: Result: index 4 is B. Index -3 is O.
Pause here. Answer before you scroll to the answers.
8.3 Strings are immutable
Once a string is made, its characters stay as they are.
You can read any letter. You cannot overwrite one letter inside the same object.
Immutable means “not changeable in place”.
Think of a printed label. You can read it. You cannot rub one letter off. You print a new label instead.
How to read the figure. The top row tries item assignment: word[0] = "C". Python raises TypeError. The boxes stay BAG.
The bottom row builds "C" + word[1:]. The name word now points at CAG. The old BAG is not edited.
How to read the flow. The third box is the error. The last box is the fix.
word = "BAG"
print(word)
try:
word[0] = "C"
except TypeError as err:
print(type(err).__name__)
print(err)
print(word)BAG
TypeError
'str' object does not support item assignment
BAGThe last print still shows BAG. You can point the same name at a new string. That is not editing the old object.
word = "BAG"
print(word)
word = "C" + word[1:]
print(word)BAG
CAGMethods such as upper look as if they change the text. They return a new string. Store the result if you need it.
word = "bag"
print(word.upper())
print(word)BAG
bagMethods never rewrite a string in place. Store the result if you need it.
- Immutable: cannot be changed after it is created.
- Item assignment: writing a new value into one index slot.
- Return: give a new value back from a function or method.
Why does word = word + "s" work, if strings are immutable?
Goal. Explain a line that looks like an edit.
Rule. + builds a new string. = then moves the name.
Old object. The first string is left unchanged.
New object. The name word now points at the longer string.
Result: Result: it replaces the name, not the old characters.
Write a short answer. Then check the notes below.
8.4 String operations
You can join strings, repeat them, test membership, and cut slices.
An operator is a symbol that does a job, such as + or *.
Concatenation means joining end to end. The operator is +.
Both sides must be strings. The originals stay the same.
left = "note"
right = "book"
joined = left + right
print(joined)
print(left)
print(right)
print("GAME" + " " + "DAY")notebook
note
book
GAME DAYjoined is notebook. left and right are unchanged.
Repetition copies a string a whole number of times. The operator is *.
One side is a string. The other side is an integer.
print("GO" * 3)
print(3 * "ha")
print(len("GO" * 3))
print("GO" * 0)
print("" + "bag")
print("bag" + "")GOGOGO
hahaha
6
bag
bag"GO" * 3 has length . Times 0 is empty. Adding "" leaves the other string as it is.
Membership tests whether a short string sits inside a longer one.
in is True when it does. not in is True when it does not.
The short string is called a substring when it is found inside.
text = "GAME DAY"
print("DAY" in text)
print("G" in text)
print("Z" in text)
print("night" not in text)
print("GAME" not in text)True
True
False
True
FalseSlicing copies part of a string. Write text[start:stop].
The character at start is kept. The character at stop is not.
The number of kept characters is when both ends lie inside and start is smaller than stop.
How to read the figure. Coloured boxes are kept. Start is kept. Stop is not.
Count: letters: O, T, E, B.
word = "NOTEBOOK"
print(word[1:5])
print(word[7:10])
print(word[3:20])
print(word[7:2])
print(word[:4])
print(word[4:])
print(len(word[1:5]))OTEB
K
EBOOK
NOTE
BOOK
4Omit start and the slice begins at 0. Omit stop and it runs to the end.
If start is larger than stop and the step is positive, the slice is empty. That is why word[7:2] is empty.
A third number is the step. Default step is 1. Step 2 skips letters. Step walks backwards.
word = "NOTEBOOK"
print(word[0:8:2])
print(word[0:8:3])
print(word[-4:-1])
print(word[::-1])NTBO
NEO
BOO
KOOBETONword[::-1] is a reversed copy. The original is not changed.
Strings can be compared with ==, !=, <, >, <=, and >=.
Python uses dictionary order and UNICODE numbers. Case matters.
print("BAG" < "CAT")
print("NOTE" == "NOTE")
print("NOTE" == "note")
print("A" < "B")
print("AB" < "AC")True
True
False
True
True| Write this | What you get |
|---|---|
| text + other | the two strings joined |
| text * n | text copied n times |
| piece in text | True if piece is inside text |
| piece not in text | True if piece is not inside |
| text[a:b] | from index a up to but not index b |
| text[a:b:k] | the same, keeping every kth character |
| text[::-1] | a reversed copy |
| s == t | True when every character matches |
The stop index is not kept. Always count start, then stop minus one.
- Concatenation: joining two strings with +.
- Repetition: copying a string n times with *.
- Membership: the in and not in tests.
- Substring: a string that sits inside another string.
- Slicing: copying a range of characters.
- Step: how many places to jump in a slice.
For NOTEBOOK, trace word[1:5] index by index. Then state word[4:] and the reverse.
Goal. Name every kept index, then two more slices.
Map. 0 N, 1 O, 2 T, 3 E, 4 B, 5 O, 6 O, 7 K.
Window. start , stop . Keep 1, 2, 3, 4. Drop 5. Count .
Letters. 1 is O, 2 is T, 3 is E, 4 is B. So word[1:5] is OTEB.
From 4. word[4:] keeps 4 to the end: B O O K.
Reverse. step walks 7 to 0: KOOBETON.
Result: Result: word[1:5] is OTEB. word[4:] is BOOK. word[::-1] is KOOBETON.
Test yourself on these. Then read the explained answers.
8.5 Traversing a string
Traversing means visiting every character, one after another.
To traverse a string is to walk through it.
You can use a for loop or a while loop. A loop repeats a short job.
How to read the figure. Box 2 is the work. Box 3 moves on. The last box stops.
A for loop can pull each character directly. You do not type the indices. It stops after the last character.
word = "BAG"
for ch in word:
print(ch)
print("done")B
A
G
doneIf you want the letters on one line, print with end="".
word = "NOTEBOOK"
for ch in word:
print(ch, end="")
print()NOTEBOOKA while loop needs an index you update yourself. Start at 0. Repeat while the index is less than the length. After each character, add 1.
word = "NOTEBOOK"
index = 0
while index < len(word):
print(word[index], end="")
index += 1
print()
print("index at the end:", index)NOTEBOOK
index at the end: 8At the end, index equals the length (8). Use <, not <=. Last valid index is 7.
To walk backwards, start at length minus one. Stop when the index goes below 0.
word = "BAG"
index = len(word) - 1
while index >= 0:
print(word[index], end="")
index -= 1
print()GAB==If you forget index += 1, the while loop never ends.==
- Traverse: visit each character in order.
- for loop: a loop that can walk through a string directly.
- while loop: a loop that repeats while a test is True.
Trace a while loop on BAG. List the index and the character each time.
Goal. Show each round of while index < len(word).
Length. len("BAG") is 3. Last valid index is 2.
Round 1. index is 0. Character is B. Then index becomes 1.
Round 2. index is 1. Character is A. Then index becomes 2.
Round 3. index is 2. Character is G. Then index becomes 3.
Stop. 3 < 3 is False. The loop ends.
Result: Result: 0:B, 1:A, 2:G. Then index is 3 and the loop stops.
Predict first. Then compare with the notes.
8.6 String methods and built-in functions
A method is a built-in action that belongs to a string.
A function is a named action, such as len(word). A method is called on the string with a dot, such as word.upper().
Methods return new values. They do not edit the original.
A rising line from 0 to 8. Each step to the right takes one more letter from NOTEBOOK. The height is the length of that prefix.
How to read the plot. One step right adds 1 to the height. Zero letters give length 0. Eight letters give length 8.
len is a function. capitalize, title, upper and lower are methods.
capitalize makes the first character uppercase and the rest lowercase.
title makes the first letter of every word uppercase.
text = "mIxEd row"
print(len(text))
print(text.capitalize())
print(text.title())
print(text.upper())
print(text.lower())
print(text)9
Mixed row
Mixed Row
MIXED ROW
mixed row
mIxEd rowfind returns the first index of a substring, or if it is missing. index does the same search, but missing text raises ValueError.
count tells how many times the substring appears. Extra start and stop indices can limit the search.
line = "bag tag bag"
print(line.find("bag"))
print(line.find("bag", 4))
print(line.find("zip"))
print(line.index("tag"))
print(line.count("bag"))
print(line.count("bag", 4, 11))
print(line.count("a"))
try:
print(line.index("zip"))
except ValueError as err:
print(type(err).__name__)
print(err)0
8
-1
4
2
1
3
ValueError
substring not foundcount("bag", 4, 11) looks from 4 up to, but not including, 11. The first bag is at 0, so this count is 1.
replace builds a new string with every match swapped. strip drops end spaces. lstrip and rstrip drop one side only. Middle spaces stay.
split cuts a string into a list of pieces (a row in square brackets). With no argument it cuts on spaces. join glues pieces with a separator.
messy = " bag tag "
print(messy.strip())
print(messy.lstrip())
print(messy.rstrip())
print("bag tag bag".replace("bag", "box"))
print("red green blue".split())
print("a-b-c".split("-"))
print("-".join(["red", "green", "blue"]))
print("-".join("BAG"))bag tag
bag tag
bag tag
box tag box
['red', 'green', 'blue']
['a', 'b', 'c']
red-green-blue
B-A-Gisalnum is True when every character is a letter or a digit, and the string is not empty. A space or a mark makes it False. startswith and endswith look at the two ends.
print("Bag2".isalnum())
print("Bag 2".isalnum())
print("note".islower())
print("NOTE".isupper())
print("Note Book".istitle())
print("note book".istitle())
print((" " * 3).isspace())
print("a b".isspace())
print("NOTEBOOK".startswith("NOTE"))
print("NOTEBOOK".endswith("BOOK"))
print("NOTEBOOK".endswith("note"))True
False
True
True
True
False
True
False
True
True
Falsepartition splits at the first match into three pieces: before, the match, and after. If the match is missing, you get the whole string and two empty strings.
print("red-green-blue".partition("-"))
print("red-green-blue".partition("Z"))('red', '-', 'green-blue')
('red-green-blue', '', '')| Name | Job |
|---|---|
| len(s) | how many characters |
| s.capitalize() | first character upper; rest lower |
| s.title() | first letter of each word upper |
| s.upper() / s.lower() | all upper or all lower |
| s.find(t) | first index of t, or -1 |
| s.index(t) | first index of t, or ValueError |
| s.count(t) | how many times t appears |
| s.replace(a, b) | new string with a swapped for b |
| s.strip() | drop end spaces |
| s.split() | list of pieces |
| sep.join(parts) | glue parts with sep |
| s.isalnum() | letters and digits only |
How to read the table. Left column is the call. Right column is the job. Use find when missing text is normal. Use index when missing text should be an error.
find returns -1 when a piece is missing. index raises ValueError.
- Method: an action called on a value with a dot.
- Built-in function: a ready-made action such as len.
- List: a row of values written in square brackets.
The string is "mIxEd row". Predict capitalize and title. Does the original change?
Goal. Name two method results, then the stored value.
Rule. Methods return a new string. They do not store it unless you assign.
capitalize. First character upper, rest lower: Mixed row.
title. First letter of each word upper: Mixed Row.
Check. The name still holds mIxEd row.
Result: Result: Mixed row and Mixed Row. The original stays mIxEd row.
Say the output aloud. Then read the answer notes.
8.7 Handling strings
Small programs can count, reverse, and test a string.
Now put the ideas together. Each program uses a user-defined function (def). The samples are fixed, so the printed output is always the same.
A vowel here is one of a, e, i, o, u, either case. Walk each character. If it sits in that set, add 1 to a counter.
def count_vowels(text):
n = 0
for ch in text:
if ch in "aeiouAEIOU":
n += 1
return n
print(count_vowels("Notebook"))
print(count_vowels("rhythm"))
print(count_vowels("AEIOU"))4
0
5Notebook has 4 vowels: o, e, o, o. y in rhythm is not in aeiou, so it is not counted.
One way is a slice with step . Another way builds a new string from the last index down to the first. Both make a new string, because the original is immutable.
def reverse_text(text):
out = ""
for i in range(-1, -len(text) - 1, -1):
out += text[i]
return out
print(reverse_text("SIGNAL"))
print("SIGNAL"[::-1])
print(reverse_text("BAG"))LANGIS
LANGIS
GABA palindrome reads the same forwards and backwards. LEVEL is one. NOTES is not. Compare first with last, then move inwards.
def is_palindrome(text):
i = 0
j = len(text) - 1
while i <= j:
if text[i] != text[j]:
return False
i += 1
j -= 1
return True
print(is_palindrome("LEVEL"))
print(is_palindrome("NOTES"))
print(is_palindrome("noon"))
print(is_palindrome("Noon"))True
False
True
Falsenoon is a palindrome. Noon is not, because N and n differ. For a case-blind test, call lower first.
def is_palindrome_quiet(text):
folded = text.lower()
return folded == folded[::-1]
print(is_palindrome_quiet("Noon"))
print(is_palindrome_quiet("Note"))True
FalseYou cannot edit in place, so you build a new string. Keep consonants. Swap each vowel for *.
def hide_vowels(text):
out = ""
for ch in text:
if ch in "aeiouAEIOU":
out += "*"
else:
out += ch
return out
print(hide_vowels("Notebook"))
print(hide_vowels("BAG"))N*t*b**k
B*GWalk each character. If ch.isdigit() is True, add int(ch).
def digit_sum(text):
total = 0
for ch in text:
if ch.isdigit():
total += int(ch)
return total
print(digit_sum("gate 2, door 14"))
print(digit_sum("NOTEBOOK"))
print(digit_sum("2026"))7
0
10In 2026 the digits are 2, 0, 2 and 6. The sum is 10. In NOTEBOOK there are no digits, so the sum is 0.
Build a new string. Copy every character except the one you drop. Do not delete in place.
def delete_char(text, mark):
out = ""
for ch in text:
if ch != mark:
out += ch
return out
print(delete_char("NOTEBOOK", "O"))
print(delete_char("GAME DAY", " "))NTEBK
GAMEDAYPalindrome tests care about case and spaces. Fold case only if you mean to.
- User-defined function: a function you write with def.
- Vowel: one of a, e, i, o, u (either case) in this chapter.
- Palindrome: a string that reads the same forwards and backwards.
- Counter: an integer you add to as you count.
- Digit: a character from 0 to 9.
Trace count_vowels("Notebook") and reverse_text("SIGNAL") step by step.
Goal. Show the counter and the growing reverse string.
Count rule. Add 1 only when the character sits in aeiouAEIOU.
N. not a vowel. n stays 0.
o. vowel. n becomes 1.
t. no. e. vowel. n becomes 2.
b. no. o. vowel. n becomes 3.
o. vowel. n becomes 4. k. no.
Count result. 4.
Reverse rule. i runs , , …, because len("SIGNAL") is 6.
Grow. L, then LA, then LAN, then LANG, then LANGI, then LANGIS.
Result: Result: count is 4. reverse_text("SIGNAL") is LANGIS.
Work on paper. Check each step against the notes.
Summary
- A string is a UNICODE sequence of characters, made with single, double or triple quotes.
- Python has no character type: one letter is a string of length 1. Spaces and digits are characters too.
- Indexing reads one character. Left indices run from 0 to n-1. Right indices run from -1 to -n.
- An index that is out of range raises IndexError. A non-integer index raises TypeError.
- Strings are immutable. Changing one slot raises TypeError. Methods return new strings.
- + concatenates. * repeats. in and not in test membership. Slices use start:stop:step. The stop index is excluded.
- Traverse with for ch in text, or with a while loop and an index.
- len, capitalize, title, upper, lower, find, index, count, replace, strip, split, join, isalnum and related tests are the everyday tools.
- find returns -1 when a piece is missing; index raises ValueError. count, find and index can take start and stop limits.
- Small programs can count vowels, reverse text, hide vowels, sum digits, delete a character, and test palindromes. Palindrome checks care about case and spaces.
Exercises
These questions are new. Show your thinking. For programs, write your answer before you run the code.
8.1 What is a string in Python?
8.2 Write one string using triple quotes that covers two lines. Show that a line break is inside it.
8.3 The string is NOTEBOOK. Give the character at index 0, index 7, and index -2.
8.4 Why is word[len(word)] an error, and which error is it?
8.5 Read this program. What three lines does it print?
word = "NOTEBOOK"
print(word[1:5])
print(word[::-1])
print("BOOK" in word)8.6 Join, repeat, and membership sit in one listing. What three lines print?
print("GO" * 3)
print("GO" + "AL")
print("Z" not in "GOAL")8.7 The string s is Night Train. What are the first four printed lines?
s = "Night Train"
print(s[0:len(s)])
print(s[-5:-1])
print(s[::2])
print(s[len(s)-1])8.8 Same string Night Train. What do the next three prints show?
s = "Night Train"
print(2 * s)
print(s[::-2])
print(s[:3] + s[3:])8.9 Same string Night Train. Finish with swapcase, startswith, and isalpha.
s = "Night Train"
print(s.swapcase())
print(s.startswith("Night"))
print(s.isalpha())8.10 The string s is Desk A,Desk B,Desk A. What do lower, upper, and count print?
s = "Desk A,Desk B,Desk A"
print(s.lower())
print(s.upper())
print(s.count("Desk"))8.11 Same desk string. What do find, rfind, and split print?
s = "Desk A,Desk B,Desk A"
print(s.find("Desk"))
print(s.rfind("Desk"))
print(s.split(","))8.12 Same desk string. Two results, then the error type from index("Hall").
s = "Desk A,Desk B,Desk A"
print(s.replace("Desk","Gate"))
print(s.partition(","))
try:
print(s.index("Hall"))
except ValueError as err:
print(type(err).__name__)8.13 Case and strip in one listing. What three lines print?
print("mixed CASE".capitalize())
print("mixed CASE".title())
print(" pad ".strip())8.14 isalnum and join. What three lines print?
print("note2".isalnum())
print("note 2".isalnum())
print("*".join(["a", "b", "c"]))8.15 A while loop prints BAG one letter per line. What values does index take, and when does the loop stop?
8.16 This vowel counter uses Notebook. What number prints?
def count_vowels(text):
n = 0
for ch in text:
if ch in "aeiouAEIOU":
n += 1
return n
print(count_vowels("Notebook"))8.17 Three palindrome tests. Which print True or False?
print("LEVEL" == "LEVEL"[::-1])
print("NOTES" == "NOTES"[::-1])
print("Noon" == "Noon"[::-1])8.18 Why can you concatenate with + but not assign to word[0]?
8.19 digit_sum on two samples. What two numbers print?
def digit_sum(text):
total = 0
for ch in text:
if ch.isdigit():
total += int(ch)
return total
print(digit_sum("gate 2, door 14"))
print(digit_sum("2026"))8.20 delete_char drops every O from NOTEBOOK. What string prints?
def delete_char(text, mark):
out = ""
for ch in text:
if ch != mark:
out += ch
return out
print(delete_char("NOTEBOOK", "O"))Answers
- 8.1: A sequence of UNICODE characters, written in quotes.
- 8.2: A string such as three double quotes around bag on / the hook, with a real break after on. len counts the break as one character.
- 8.3: N, K, and O.
- 8.4: The last valid index is length minus one. IndexError.
- 8.5: prints OTEB, then KOOBETON, then True
- 8.6: prints GOGOGO, then GOAL, then True
- 8.7: prints Night Train, then Trai, then NgtTan, then n
- 8.8: prints Night TrainNight Train, then naTtgN, then Night Train
- 8.9: prints nIGHT tRAIN, then True, then False
- 8.10: prints desk a,desk b,desk a, then DESK A,DESK B,DESK A, then 3
- 8.11: prints 0, then 14, then ['Desk A', 'Desk B', 'Desk A']
- 8.12: prints Gate A,Gate B,Gate A, then ('Desk A', ',', 'Desk B,Desk A'), then ValueError
- 8.13: prints Mixed case, then Mixed Case, then pad
- 8.14: prints True, then False, then abc
- 8.15: index is 0, then 1, then 2. After printing G it becomes 3, which is not less than len 3, so the loop stops.
- 8.16: prints 4
- 8.17: prints True, then False, then False
- 8.18: + builds a new string. Assigning to an index would edit the old string, and strings are immutable, so Python raises TypeError.
- 8.19: prints 7, then 10
- 8.20: prints NTEBK