Objectives: LO-6.1, LO-6.2, LO-6.3, LO-6.4
Prerequisites: Module 5
Time: about 5.5 hours: 2 for this reading, 2 for Lab 6, and 1.5 for the
practice
Part 2 of the course is about data, and text is the data most programs meet first: names,
messages, answers typed at a prompt, and the lines of a file. You have already joined strings
with +, repeated them with *, measured them with len, looped over their characters, and
compared them. This module takes strings apart. You will pick out single characters and pieces of
a string, search and change text with string methods, and process text one character or one word
at a time. The module ends with what a character is to Python, which explains some surprises with
accented letters and emoji.
Indexing: one character at a time¶
A string is a sequence: its characters come in order, and each has a position, called its index, counted from 0. Square brackets after a string pick out the character at an index:
word = "Python"
print(word[0])
print(word[1])
print(word[5])P
y
nEach index counts how many characters come before that one. The first character has none before it, so its index is 0. For a string of length , the indices run from 0 to :
character: P y t h o n
index: 0 1 2 3 4 5
negative: -6 -5 -4 -3 -2 -1An index past the end is an error. "Python" has six characters, so its last index is 5, and
word[6] stops with:
IndexError: string index out of rangeAn index must be a whole number: word[1.5] stops with
TypeError: string indices must be integers, not 'float'.
Negative indices¶
A negative index counts from the end, as the table’s last row shows: word[-1] is the last
character, "n", and word[-2] is "o". word[-1] means the same as word[len(word) - 1], and
is shorter and harder to get wrong. Negative indices stop at the start of the string: word[-7] is
an IndexError too.
Indices in a loop¶
A for loop over a string gives its characters, as Module 4 showed. When a character’s position
matters, loop over the indices instead, with range(len(text)). This loop counts the places where
a letter is the same as the one after it:
word = "bookkeeper"
doubles = 0
for i in range(len(word) - 1):
if word[i] == word[i + 1]:
doubles = doubles + 1
print(doubles)3The pairs are oo, kk, and ee. The loop stops one index early, at len(word) - 2, because
it reads word[i + 1]. With range(len(word)), the last pass would read word[10] and stop with
an IndexError.
Slicing: a piece of a string¶
A slice gives a new string made of a run of characters. text[start:stop] starts at index
start and stops just before index stop, the same rule range follows:
word = "Python"
print(word[0:2])
print(word[2:6])Py
thonLeave out
startto begin at the start, andstopto go to the end:word[:2]is"Py", andword[2:]is"thon". Because the stop is left out of the slice,word[:k] + word[k:]is the whole word for anyk, just asrange(0, 5)andrange(5, 10)fit together.Negative indices work in slices:
word[-3:]is the last three characters,"hon".A slice is never an
IndexError. A stop past the end stops at the end, soword[1:100]is"ython", and a slice whose start is at or after its stop is empty:word[4:2]is"".When both ends are in range,
text[a:b]hasb - acharacters.
Worked example: the parts of a date¶
A date written as "2026-12-04" (year, month, and day, the ISO 8601 format) always puts the year
at indices 0 to 3, the month at 5 and 6, and the day at 8 and 9:
date = "2026-12-04"
year = int(date[0:4])
month = int(date[5:7])
day = int(date[8:10])
print(day, month, year)4 12 2026Each slice stops at the index of the first character it doesn’t want: the hyphen at 4, the hyphen
at 7, and the end, 10. int("04") is 4. Slicing works here only because the format fixes every
position. Module 9 shows the datetime module, which reads dates in many formats and checks them.
Steps¶
A third number in a slice is a step, as in range: text[start:stop:step] takes every
step-th character. word[::2] is "Pto", the characters at 0, 2, and 4.
A negative step goes backward, from start down to just before stop. word[5:1:-1] is
"noht". With both ends left out, word[::-1] is the whole string reversed, "nohtyP": the
shorter way to reverse a string that Module 4’s practice promised. A word that reads the same
both ways, such as "level", is a palindrome, and text == text[::-1] tests for one.
Strings can’t be changed¶
Try to change one character of a string:
word = "Python"
word[0] = "J"TypeError: 'str' object does not support item assignmentStrings are immutable: once a string exists, it never changes. Every operation that seems to
change a string makes a new one instead. To get "Jython", build it from pieces:
word = "J" + word[1:]This assignment doesn’t change the old string either. It builds a new string, "Jython", and
makes word refer to it, as Module 2 showed: a name refers to a value, and assignment points the
name at a different value.
Immutability is a design choice. Because no code can change a string, many names, and many parts of a program, can share one string safely: none of them can change it under the others. Module 8 relies on this, because dictionary keys must not change. Lists, in Module 7, can be changed, and Module 7 shows what that costs.
String methods¶
A method is a function that belongs to a type of value. You call it with a dot after a value
of that type: text.upper() calls the upper method of the string text. Strings have 47
methods; this section covers the ones you will use most, and the library
documentation lists them all.
Because strings are immutable, a string method never changes its string. It returns a new one:
name = "ada lovelace"
print(name.upper())
print(name)ADA LOVELACE
ada lovelaceTo keep the result, assign it: name = name.upper(). A method call on a line of its own, such as
name.upper(), builds the new string and throws it away, so in a script it does nothing you can
see.
Changing case and removing spaces¶
lower()andupper()return the string in lowercase or in capitals. Uselower()to compare text without caring about case:answer.lower() == "yes"isTruefor"Yes","YES", and"yes".strip()returns the string without the whitespace (spaces, tabs, and newlines) at either end.lstrip()strips only the left end, andrstrip()only the right. None of them touches spaces between words. Typed answers and lines read from files often carry extra spaces or a newline at the end.Given an argument,
stripremoves any of the characters in it from both ends:"...Wow!!".strip(".!")is"Wow". The argument is a set of characters, not a word to remove:"banana".strip("an")is"b".
Each method returns a string, so you can call another method on its result. These chained calls run from left to right:
answer = " YES \n"
print(answer.strip().lower() == "yes")TrueSearching¶
inasks whether one string appears inside another:"an" in "banana"isTrue, and"nab" in "banana"isFalse. Module 4 usedinwith one character; it works with a string of any length.not inasks the opposite.find(sub)returns the index wheresubfirst appears, or -1 if it doesn’t appear:"banana".find("an")is 1, and"banana".find("x")is -1. Check for -1 before you use the result, because -1 is also a valid index:text[text.find("x")]quietly gives the last character oftext.count(sub)returns how many timessubappears, without overlaps:"banana".count("a")is 3, and"banana".count("an")is 2.startswith(prefix)andendswith(suffix)ask whether a string begins or ends with another:"report.pdf".endswith(".pdf")isTrue.
All of them, and in, tell capitals from lowercase letters: "Report".startswith("rep") is
False, but "Report".lower().startswith("rep") is True.
Replacing¶
replace(old, new) returns a copy with every old replaced by new: "banana".replace("a", "o") is "bonono". A third argument limits how many are replaced, from the left:
"banana".replace("a", "o", 1) is "bonana". Replacing with the empty string deletes:
"1,250,000".replace(",", "") is "1250000", which int can read.
Splitting and joining¶
split(), with no argument, splits a string at each run of whitespace, ignores whitespace at the
ends, and returns the pieces as a list:
print(" one two three ".split())['one', 'two', 'three']A list is an ordered collection of values, written in square brackets. Module 7 covers lists
fully; for now, a for loop goes through a list’s items in order, len gives how many it has,
and indices and slices work on it as they do on a string.
With an argument, split(sep) splits at every sep exactly. Two separators side by side leave an
empty string between them: "a,b,,c".split(",") is ['a', 'b', '', 'c']. That is what you want
for data with a fixed separator, such as comma-separated values, where an empty field still
counts. (Module 11 shows the csv module, which also handles commas inside quoted fields.)
join does the reverse: sep.join(items) joins a list of strings with sep between each pair:
print("-".join(["2026", "12", "04"]))
print(" ".join(" one two three ".split()))2026-12-04
one two threeThe separator is the string you call join on, so it is ", ".join(words), not
words.join(", "). Every item must be a string: " ".join([1, 2]) stops with
TypeError: sequence item 0: expected str instance, int found. The second line above is a common
idiom: splitting and joining again turns every run of whitespace into one space.
Testing what kind of characters a string has¶
isalpha(), isdigit(), and isspace() return True when the string isn’t empty and every
character in it is of that kind: "123".isdigit() is True, but "12.5".isdigit() is False,
because a point isn’t a digit, and "".isdigit() is False. isupper() and islower() look
only at the letters, and need at least one: "A1".isupper() is True, and "123".isupper() is
False.
These methods follow Unicode, the standard for the world’s characters that the last section of
this module explains, not only the English alphabet. "é".isalpha() is True, and so is
"²".isdigit(), though int("²") fails. When only A to Z or 0 to 9 will do, test each character
with in "0123456789", as PA1 did. Module 12 shows the surest way to check that int accepts a
string: try the conversion, and handle the error if it fails.
The methods at a glance¶
| Method | Returns | Example | Result |
|---|---|---|---|
lower(), upper() | The string in lowercase or capitals | "Hi".upper() | "HI" |
strip(), lstrip(), rstrip() | The string without whitespace at both ends, the left, or the right | " hi \n".strip() | "hi" |
find(sub) | The index of the first sub, or -1 | "banana".find("n") | 2 |
count(sub) | How many times sub appears | "banana".count("a") | 3 |
startswith(p), endswith(s) | Whether the string starts with p or ends with s | "a.py".endswith(".py") | True |
replace(old, new) | A copy with every old replaced by new | "a-b".replace("-", "") | "ab" |
split(), split(sep) | A list of the pieces between whitespace, or between each sep | "a b".split() | ['a', 'b'] |
sep.join(items) | The strings in items, with sep between them | "+".join(["a", "b"]) | "a+b" |
isalpha(), isdigit() | Whether every character is a letter, or a digit | "a1".isalpha() | False |
Processing text one character at a time¶
Module 4’s loop patterns all work on strings, because a for loop over a string gives one
character at a time.
Counting¶
A counter for each kind of character:
text = "Room 101, floor 3"
letters = 0
digits = 0
for character in text:
if character.isalpha():
letters = letters + 1
elif character.isdigit():
digits = digits + 1
print(letters, digits, len(text) - letters - digits)9 4 4The last number counts everything else: three spaces and a comma.
Building a new string¶
Because a string can’t be changed, cleaning text means building a new string. Start with the empty string and add each character you want to keep, the accumulator pattern from Module 4:
def letters_and_spaces(text):
"""Return text without the characters that are neither letters nor spaces."""
kept = ""
for character in text:
if character.isalpha() or character == " ":
kept = kept + character
return kept
cleaned = letters_and_spaces("It's 9:30 -- time to go!")
print(repr(cleaned))
print(repr(" ".join(cleaned.split())))'Its time to go'
'Its time to go'repr shows a string with its quotes, so the spaces are visible. Removing 9:30 and -- left
three spaces in a row, and splitting and joining turned them into one.
Validating¶
To validate text is to check that it has the form you expect before you use it. Suppose a
product code is two capital letters from A to Z, a hyphen, and four digits, as in "AB-1234":
CAPITALS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
DIGITS = "0123456789"
def is_product_code(code):
"""Return True if code is two capitals A-Z, a hyphen, and four digits, as in AB-1234."""
if len(code) != 7 or code[2] != "-":
return False
for character in code[:2]:
if character not in CAPITALS:
return False
for character in code[3:]:
if character not in DIGITS:
return False
return True
assert is_product_code("AB-1234")
assert not is_product_code("ab-1234")
assert not is_product_code("AB1234")
assert not is_product_code("AB-12345")
assert not is_product_code("ÉB-1234")
print("all tests passed")all tests passedThe function returns
Falseat the first thing wrong, andTrueonly after every check passes: Module 4’s search pattern, withreturnin place ofbreak.code[2]is safe to read, becauseorstops as soon as it knows the answer (Module 3): when the length isn’t 7, Python never readscode[2].CAPITALSandDIGITSare written in capitals to show that they never change, a convention for constants in Python."É".isupper()isTrue, socode[:2].isupper()would have accepted"ÉB-1234"; testing each character againstCAPITALSdoesn’t.
Processing text one word at a time¶
split() gives the words of a text, and a for loop goes through them. Punctuation stays stuck
to the words, so clean each word before you use it.
Worked example: words in a passage¶
A string in triple quotes, """…""", can run over several lines, and each line break becomes a
newline character in the string. (Module 5’s docstrings are strings of this kind.)
passage = """The library opens at nine. On Saturdays the library
opens at ten, and the reading room stays open late."""
words = passage.split()
the_count = 0
longest = ""
for word in words:
cleaned = word.strip(".,;:!?").lower()
if cleaned == "the":
the_count = the_count + 1
if len(cleaned) > len(longest):
longest = cleaned
print(len(words), "words")
print("the:", the_count)
print("longest:", longest)19 words
the: 3
longest: saturdayssplit()splits at the newline as well as at spaces, so"library"and"opens", on two lines, are two words.strip(".,;:!?")takes the punctuation off"nine."and"ten,", andlower()makes"The"count as"the".longestkeeps the first of two equally long words, because the test is>, not>=.
passage.lower().count("the") also gives 3 here, but only by luck. count finds "the" inside
other words too, so a passage with "there" or "other" in it would give too many. Counting
words needs the words. Counting every different word at once needs a dictionary, which Module 8
covers.
Worked example: initials¶
Indexing, methods, and a loop over words together:
def initials(full_name):
"""Return the initials of a name, as "A. K. L." for "ada king lovelace"."""
result = ""
for word in full_name.split():
result = result + word[0].upper() + ". "
return result.rstrip()
print(initials("ada king lovelace"))
print(initials(" Grace Hopper "))A. K. L.
G. H.word[0] is safe because split() never returns an empty word, and rstrip() removes the space
after the last point.
Characters and code points¶
Module 3 said that every character has a number, its code point, and that strings compare by
these numbers. ord gives the code point of a one-character string, and chr gives the
character for a code point:
print(ord("A"), ord("a"), ord("0"), ord(" "))
print(chr(65), chr(97 + 2))65 97 48 32
A cThe numbers come from Unicode, the standard that gives a number to each character of the
world’s writing systems, as well as to symbols and emoji. It has room for 1,114,112 code points,
from 0 to 1,114,111. The first 128 are the same as in ASCII, the older American standard for
English letters, digits, and punctuation. The capitals A to Z are 65 to 90, the lowercase letters
a to z are 97 to 122, and the digits 0 to 9 are 48 to 57, each run in order, so arithmetic on code
points works: chr(ord("a") + 1) is "b".
ord takes exactly one character: ord("ab") stops with
TypeError: ord() expected a character, but string of length 2 found.
Worked example: shifting a letter¶
A Caesar cipher hides a message by replacing each letter with the letter a fixed number of
places later in the alphabet, wrapping around from z to a. With a shift of 3, a becomes d, and
y becomes b. Shifting one lowercase letter takes three steps:
def shift_letter(letter, shift):
"""Return the lowercase letter shift places further along the alphabet, wrapping around."""
position = ord(letter) - ord("a")
new_position = (position + shift) % 26
return chr(ord("a") + new_position)
print(shift_letter("a", 3), shift_letter("y", 3), shift_letter("a", -3))d b xord(letter) - ord("a")turns the letter into its place in the alphabet, from 0 forato 25 forz.% 26wraps past the end: fory,(24 + 3) % 26is 1. It wraps a negative shift too, because%with a positive divisor always gives a result from 0 up to the divisor (Module 2):(0 - 3) % 26is 23.chr(ord("a") + new_position)turns the place back into a letter.
Lab 6 builds the whole cipher: messages with capitals, spaces, and punctuation, and a way to break one without knowing the shift.
Beyond ASCII¶
Code points go far beyond 127:
print(ord("é"), ord("€"), ord("🐍"))
print(chr(233), chr(128013))233 8364 128013
é 🐍Code points are usually written in hexadecimal (base 16, with the digits 0 to 9 and A to F),
after U+: é is U+00E9, € is U+20AC, and 🐍 is U+1F40D. Inside a Python string, \u followed by
four hexadecimal digits, or \U followed by eight, writes a character by its code point: "\u00e9"
is "é", and "\U0001F40D" is "🐍".
What len counts¶
A Python string is a sequence of code points, and len counts them. That is often not the number
of bytes the text takes up, and sometimes not the number of characters a reader sees.
Bytes. To store text in a file or send it over a network, a program encodes it as bytes,
nowadays almost always with UTF-8. UTF-8 stores each ASCII character in 1 byte, and every other
code point in 2, 3, or 4. encode returns the bytes, and Module 11 does this when it reads and
writes files:
print(len("café"), len("café".encode("utf-8")))
print(len("🐍"), len("🐍".encode("utf-8")))4 5
1 4What a reader sees. Some characters on screen are several code points. The é in "café"
can be one code point, U+00E9, or two: a plain e followed by U+0301, the combining acute accent,
which is drawn on top of the character before it. The two strings look the same but aren’t
equal:
one_point = "caf\u00e9"
two_points = "cafe\u0301"
print(one_point, two_points)
print(len(one_point), len(two_points), one_point == two_points)café café
4 5 FalseEmoji do this often. The waving hand with a skin tone, 👋🏽, is two code points, a hand and a
skin-tone modifier, so len("👋🏽") is 2. The flag 🇫🇷 is two code points as well, the letters F
and R from a special block of Unicode.
What a reader counts as one character, Unicode calls a grapheme cluster. Python 3.12, the
version this course uses, has no function that counts them. Python 3.15 adds one,
iter_graphemes, to the unicodedata
module.
Three consequences matter in everyday code:
A limit such as “at most 10 characters” counts code points, so it allows fewer emoji than a reader expects.
Slicing can split a character a reader sees:
two_points[:4]is"cafe", without its accent, andtwo_points[::-1]puts the accent first, where there is no letter to draw it on.Text that looks equal may not be. To compare text from different sources, first convert both with
unicodedata.normalize("NFC", text), which turns each letter and combining accent into the single code point for the accented letter, where Unicode has one.
Common misconceptions¶
| Belief | What Python does | Example that breaks it |
|---|---|---|
| A string’s first character is at index 1 | Indices start at 0 | "Python"[1] is "y" |
| The last index is the string’s length | It is the length minus 1 | "Python"[6] is an IndexError |
| A slice includes the character at its stop | It stops just before it | "Python"[0:2] is "Py" |
| A method changes its string | It returns a new string | After name.upper(), name is unchanged |
| One character of a string can be replaced | Strings are immutable | word[0] = "J" is a TypeError |
find returns False when the text isn’t there | It returns -1, which is also a valid index | text[text.find("x")] gives the last character |
strip removes a word from the ends | It removes any of the characters given | "banana".strip("an") is "b" |
split(" ") is the same as split() | split(" ") keeps an empty string between two spaces | "a b".split(" ") is ['a', '', 'b'] |
len counts the characters a reader sees | It counts code points | len("👋🏽") is 2 |
Summary¶
A string’s characters have indices from 0 to its length minus 1, and negative indices count from the end.
text[i]is one character.text[start:stop:step]is a slice: a new string fromstartup to, but not including,stop. Either end can be left out, a slice is never anIndexError, andtext[::-1]is the string reversed.Strings are immutable. Methods such as
lower,strip, andreplacereturn new strings, so keep the result by assigning it.in,find,count,startswith, andendswithsearch text;splitandjointurn text into a list of words and back.Module 4’s patterns process text one character or one word at a time: count, build a cleaned copy, and validate with an early
return.ordandchrconvert between characters and Unicode code points.lencounts code points, which can differ from the bytes the text takes up and from the characters a reader sees.
Self-check¶
Answer each question before you open its answer.
Given
s = "notebook", what ares[2],s[-1],s[2:5],s[:4], ands[::-1]?Answer
"t","k","teb","note", and"koobeton". The slices[2:5]has 5 − 2 = 3 characters, at indices 2, 3, and 4.What does this print?
name = " Grace Hopper " name.strip() print(len(name), len(name.strip()))Answer
15 12. The second line builds a stripped copy and throws it away, sonamestill has its three spaces. Only the call insideprintuses a stripped copy.Write one expression that turns
date = "2026-12-04"into"04/12/2026".Answer
date[8:] + "/" + date[5:7] + "/" + date[:4]. An f-string works as well:f"{date[8:]}/{date[5:7]}/{date[:4]}".Why is
"Zebra" < "apple"True, and how would you compare the two words ignoring case?Answer
Strings compare by code point, and
ord("Z")is 90, which is less thanord("a"), 97. Compare lowercase copies instead:"Zebra".lower() < "apple".lower()isFalse.The word “naïve” looks five characters long. Why can
lengive 5 for it in one program and 6 in another?Answer
The
ïcan be one code point, U+00EF, or two:ifollowed by U+0308, the combining diaeresis.lencounts code points, so the second form gives 6.unicodedata.normalize("NFC", text)turns the second form into the first.
Further reading¶
The Python Tutorial, section 3.1.2, Text. Indexing, slicing, and immutability in the language’s own words, with more examples.
The Python Standard Library, String Methods. Every string method, in alphabetical order. Look here when you need to know exactly what a method does with an empty string or a missing argument.
The Unicode HOWTO. Code points, encodings, UTF-8, and normalization, in more depth than this module.
Allen B. Downey, Think Python, 3rd edition, chapter 8, Strings and Regular Expressions. Sections 8.1 to 8.5 cover indexing, slicing, immutability, and methods. The rest of the chapter introduces regular expressions, a pattern language for searching text that this course doesn’t teach.
Al Sweigart, Automate the Boring Stuff with Python, 3rd edition, chapter 8, Strings and Text Editing. Escape characters, slicing, the
ismethods,joinandsplit, andordandchr, with short programs that edit text.