←
Class 11 Computer Science
8. Strings in Python · 8 / 11
⌕
Chapter 8 of 11

8. Strings in Python

10 sections · 5,562 words

About this chapter

219 words · 1 min read

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

554 words · 3 min read

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.

Why it matters: quotes tell Python “this is text”, not a name or a number.

Make a string by wrapping text in quotes.

Single quotes and double quotes both work. They make the same kind of value.

Python
a = 'bus stop'
b = "bus stop"
print(a)
print(b)
print(a == b)
print(type(a).__name__)

Output
bus stop
bus stop
True
str

a == 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.

Python
notice = """bag on
the hook"""
print(notice)
print(len(notice))

Output
bag on
the hook
15

One 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.

Python
mark = "Q"
print(type(mark).__name__)
print(len(mark))

Output
str
1

An empty string has quotes with nothing inside. Its length is 0. It is still a string.

Python
>>> len("")
0
>>> "" == ""
True

A 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.

Python
code = "204"
print(len(code))
print(code[0])
print(code[0] + code[1] + code[2])
print(type(code).__name__)

Output
3
2
204
str

Length 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.

Python
print("Student A's bag")
print('He said "go"')
print(len("Student A's bag"))

Output
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.

Watch out: Triple quotes still make one string. They do not make three strings.

⚡ Quick Check Flashcards4 questions
Question 1
In one short sentence, what is a string?
Try answering before revealing!
Question 2
Name three kinds of quotes that can wrap a string.
Try answering before revealing!
Question 3
Does Python have a separate type for one letter?
Try answering before revealing!
Question 4
What numbering system does Python use for characters in a string?
Try answering before revealing!

8.2 Accessing characters in a string

621 words · 3 min read

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 nn characters, the last index from the left is n−1n - 1.

For NOTEBOOK, n=8n = 8, so the last left index is 77.

Index from the left (starts at 0)0N-81O-72T-63E-54B-45O-36O-27K-1Index from the right (starts at -1)The same box has two numbers. Both names point at one letter.
Each letter has two addresses: one counted from the left, and one counted from the right.

How to read the figure. Box T has 2 above and −6-6 below. Both names point at T.

LetterFrom the leftFrom the right
N0-8
O1-7
T2-6
E3-5
B4-4
O5-3
O6-2
K7-1

A negative index counts from the right. The last character is −1-1.

The first character is −n-n. For NOTEBOOK that name is −8-8.

Python
word = "NOTEBOOK"
print(word[0])
print(word[3])
print(word[7])
print(word[-1])
print(word[-8])
print(word[2 + 4])

Output
N
E
K
K
N
O

word[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.

Python
print(len("NOTEBOOK"))
print(len("GAME DAY"))
label = "GAME DAY"
n = len(label)
print(label[n - 1])
print(label[-n])
print(label[4])

Output
8
8
Y
G

GAME DAY has a space at index 4. Length counts it, so the length is 8, not 7.

IndexCharacter in GAME DAY
0G
1A
2M
3E
4a space
5D
6A
7Y

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.

Python
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)

Output
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.

Why it matters: off-by-one errors are the most common string bugs.

  • 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 −1-1.

Left. 0 is N, 1 is O, 2 is T, 3 is E, 4 is B.

Right. −1-1 is K, −2-2 is O, −3-3 is O.

Result: Result: index 4 is B. Index -3 is O.

Pause here. Answer before you scroll to the answers.

Watch out: The first character is index 0. The last from the left is length minus one, not the length itself.

⚡ Quick Check Flashcards5 questions
Question 1
What is the left index of the first character?
Try answering before revealing!
Question 2
A string has 8 characters. What is the last left index?
Try answering before revealing!
Question 3
What does word[-1] give you?
Try answering before revealing!
Question 4
Which error appears if the index is 1.5?
Try answering before revealing!
Question 5
Which error appears if the index is past the end?
Try answering before revealing!

8.3 Strings are immutable

526 words · 2 min read

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.

Before and after a failed editBAGword - BAGword[0]="C"TypeErrorBAGstill BAGA new string, then a new name linkBAGC + word[1:]CAGword now points here
Item assignment fails. Building a new string and moving the name succeeds.

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.

Make a string and store it.Try to change one letter in place.Python raises TypeError.Build a new string instead.
Strings cannot be edited in place. You make a new string.

How to read the flow. The third box is the error. The last box is the fix.

Python
word = "BAG"
print(word)
try:
    word[0] = "C"
except TypeError as err:
    print(type(err).__name__)
    print(err)
print(word)

Output
BAG
TypeError
'str' object does not support item assignment
BAG

The last print still shows BAG. You can point the same name at a new string. That is not editing the old object.

Python
word = "BAG"
print(word)
word = "C" + word[1:]
print(word)

Output
BAG
CAG

Methods such as upper look as if they change the text. They return a new string. Store the result if you need it.

Python
word = "bag"
print(word.upper())
print(word)

Output
BAG
bag

Methods never rewrite a string in place. Store the result if you need it.

Why it matters: if you forget to store the new string, your program keeps the old text.

  • 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.

Watch out: Calling upper does not rewrite the original. Store the result if you need the new text.

⚡ Quick Check Flashcards4 questions
Question 1
What does immutable mean for a string?
Try answering before revealing!
Question 2
Which error do you get from word[0] = "C"?
Try answering before revealing!
Question 3
Does word.upper() change word?
Try answering before revealing!
Question 4
How can you "change" the first letter of BAG to C?
Try answering before revealing!

8.4 String operations

802 words · 4 min read

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.

Python
left = "note"
right = "book"
joined = left + right
print(joined)
print(left)
print(right)
print("GAME" + " " + "DAY")

Output
notebook
note
book
GAME DAY

joined 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.

Python
print("GO" * 3)
print(3 * "ha")
print(len("GO" * 3))
print("GO" * 0)
print("" + "bag")
print("bag" + "")

Output
GOGOGO
hahaha
6

bag
bag

"GO" * 3 has length 66. 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.

Python
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)

Output
True
True
False
True
False

Slicing 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 stop−startstop - start when both ends lie inside and start is smaller than stop.

NOTEBOOK01234567start = 1stop = 5Kept: O T E B Count: 5 - 1 = 4 letters
A slice keeps letters from start up to, but not including, stop.

How to read the figure. Coloured boxes are kept. Start =1= 1 is kept. Stop =5= 5 is not.

Count: 5−1=45-1=4 letters: O, T, E, B.

Python
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]))

Output
OTEB
K
EBOOK

NOTE
BOOK
4

Omit 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 −1-1 walks backwards.

Python
word = "NOTEBOOK"
print(word[0:8:2])
print(word[0:8:3])
print(word[-4:-1])
print(word[::-1])

Output
NTBO
NEO
BOO
KOOBETON

word[::-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.

Python
print("BAG" < "CAT")
print("NOTE" == "NOTE")
print("NOTE" == "note")
print("A" < "B")
print("AB" < "AC")

Output
True
True
False
True
True
Write thisWhat you get
text + otherthe two strings joined
text * ntext copied n times
piece in textTrue if piece is inside text
piece not in textTrue 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 == tTrue when every character matches

The stop index is not kept. Always count start, then stop minus one.

Why it matters: a slice is a copy. The original string is still there.

  • 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 =1= 1, stop =5= 5. Keep 1, 2, 3, 4. Drop 5. Count 44.

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 −1-1 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.

Watch out: The stop index is not kept. word[1:5] does not include index 5.

⚡ Quick Check Flashcards6 questions
Question 1
What does "ab" + "cd" make?
Try answering before revealing!
Question 2
What does "ha" * 3 make?
Try answering before revealing!
Question 3
Is "TAG" in "BAG TAG"?
Try answering before revealing!
Question 4
Does word[:4] include index 4?
Try answering before revealing!
Question 5
What does a step of -1 do in a slice?
Try answering before revealing!
Question 6
Is "NOTE" == "note"?
Try answering before revealing!

8.5 Traversing a string

509 words · 2 min read

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.

Start at the first character.Use the character (print it, count it, test it).Move to the next character.Stop after the last character.
Both kinds of loop follow this walk.

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.

Python
word = "BAG"
for ch in word:
    print(ch)
print("done")

Output
B
A
G
done

If you want the letters on one line, print with end="".

Python
word = "NOTEBOOK"
for ch in word:
    print(ch, end="")
print()

Output
NOTEBOOK

A 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.

Python
word = "NOTEBOOK"
index = 0
while index < len(word):
    print(word[index], end="")
    index += 1
print()
print("index at the end:", index)

Output
NOTEBOOK
index at the end: 8

At 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.

Python
word = "BAG"
index = len(word) - 1
while index >= 0:
    print(word[index], end="")
    index -= 1
print()

Output
GAB

==If you forget index += 1, the while loop never ends.==

Why it matters: a for loop is safer for a full walk. Use while when you must control the index.

  • 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.

Watch out: If you forget index += 1 in a while loop, the loop never ends. The same character prints forever.

⚡ Quick Check Flashcards4 questions
Question 1
What does traverse mean?
Try answering before revealing!
Question 2
Which loop can walk a string without you writing an index?
Try answering before revealing!
Question 3
When does while index < len(word) stop?
Try answering before revealing!
Question 4
How do you print characters on one line in a loop?
Try answering before revealing!

8.6 String methods and built-in functions

831 words · 4 min read

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.

Prefix length of NOTEBOOK. Taking k letters from the left always gives a string of length k. This is a model of len, not a measured experiment.

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.

Python
text = "mIxEd row"
print(len(text))
print(text.capitalize())
print(text.title())
print(text.upper())
print(text.lower())
print(text)

Output
9
Mixed row
Mixed Row
MIXED ROW
mixed row
mIxEd row

find returns the first index of a substring, or −1-1 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.

Python
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)

Output
0
8
-1
4
2
1
3
ValueError
substring not found

count("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.

Python
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"))

Output
bag tag
bag tag  
  bag tag
box tag box
['red', 'green', 'blue']
['a', 'b', 'c']
red-green-blue
B-A-G

isalnum 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.

Python
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"))

Output
True
False
True
True
True
False
True
False
True
True
False

partition 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.

Python
print("red-green-blue".partition("-"))
print("red-green-blue".partition("Z"))

Output
('red', '-', 'green-blue')
('red-green-blue', '', '')
NameJob
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.

Why it matters: mix find and index, and a missing word can crash a program.

  • 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.

Watch out: find returns -1 when the piece is missing. index raises ValueError. Do not mix them up.

⚡ Quick Check Flashcards5 questions
Question 1
What is the difference between capitalize and title?
Try answering before revealing!
Question 2
What does find return when the substring is missing?
Try answering before revealing!
Question 3
What does index do when the substring is missing?
Try answering before revealing!
Question 4
Does strip remove spaces in the middle?
Try answering before revealing!
Question 5
What does "-".join("BAG") print?
Try answering before revealing!

8.7 Handling strings

693 words · 3 min read

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.

Python
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"))

Output
4
0
5

Notebook 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 −1-1. Another way builds a new string from the last index down to the first. Both make a new string, because the original is immutable.

Python
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"))

Output
LANGIS
LANGIS
GAB

A palindrome reads the same forwards and backwards. LEVEL is one. NOTES is not. Compare first with last, then move inwards.

Python
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"))

Output
True
False
True
False

noon is a palindrome. Noon is not, because N and n differ. For a case-blind test, call lower first.

Python
def is_palindrome_quiet(text):
    folded = text.lower()
    return folded == folded[::-1]

print(is_palindrome_quiet("Noon"))
print(is_palindrome_quiet("Note"))

Output
True
False

You cannot edit in place, so you build a new string. Keep consonants. Swap each vowel for *.

Python
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"))

Output
N*t*b**k
B*G

Walk each character. If ch.isdigit() is True, add int(ch).

Python
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"))

Output
7
0
10

In 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.

Python
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", " "))

Output
NTEBK
GAMEDAY

Palindrome tests care about case and spaces. Fold case only if you mean to.

Why it matters: a real check must say whether spaces and case count.

  • 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 −1-1, −2-2, …, −6-6 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.

Watch out: Palindrome tests are case-sensitive unless you fold case first. Spaces count as characters too.

⚡ Quick Check Flashcards5 questions
Question 1
How many vowels does rhythm have in this chapter's rule?
Try answering before revealing!
Question 2
Why must reverse build a new string?
Try answering before revealing!
Question 3
Is Noon a palindrome without changing case?
Try answering before revealing!
Question 4
What does hide_vowels("BAG") print?
Try answering before revealing!
Question 5
What is digit_sum("2026")?
Try answering before revealing!

Summary

188 words · 1 min read
  • 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.
Explain each important word in your own words. Then say why the rule works.

Exercises

619 words · 3 min read

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?

Python
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?

Python
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?

Python
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?

Python
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.

Python
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?

Python
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?

Python
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").

Python
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?

Python
print("mixed CASE".capitalize())
print("mixed CASE".title())
print("  pad  ".strip())

8.14 isalnum and join. What three lines print?

Python
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?

Python
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?

Python
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?

Python
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?

Python
def delete_char(text, mark):
    out = ""
    for ch in text:
        if ch != mark:
            out += ch
    return out
print(delete_char("NOTEBOOK", "O"))

Answers

  1. 8.1: A sequence of UNICODE characters, written in quotes.
  2. 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.
  3. 8.3: N, K, and O.
  4. 8.4: The last valid index is length minus one. IndexError.
  5. 8.5: prints OTEB, then KOOBETON, then True
  6. 8.6: prints GOGOGO, then GOAL, then True
  7. 8.7: prints Night Train, then Trai, then NgtTan, then n
  8. 8.8: prints Night TrainNight Train, then naTtgN, then Night Train
  9. 8.9: prints nIGHT tRAIN, then True, then False
  10. 8.10: prints desk a,desk b,desk a, then DESK A,DESK B,DESK A, then 3
  11. 8.11: prints 0, then 14, then ['Desk A', 'Desk B', 'Desk A']
  12. 8.12: prints Gate A,Gate B,Gate A, then ('Desk A', ',', 'Desk B,Desk A'), then ValueError
  13. 8.13: prints Mixed case, then Mixed Case, then pad
  14. 8.14: prints True, then False, then abc
  15. 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.
  16. 8.16: prints 4
  17. 8.17: prints True, then False, then False
  18. 8.18: + builds a new string. Assigning to an index would edit the old string, and strings are immutable, so Python raises TypeError.
  19. 8.19: prints 7, then 10
  20. 8.20: prints NTEBK
Up next
Continue to the next chapter