Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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
n

Each 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 nn, the indices run from 0 to n−1n - 1:

character:   P   y   t   h   o   n
    index:   0   1   2   3   4   5
 negative:  -6  -5  -4  -3  -2  -1

An 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 range

An 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)
3

The 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
thon

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 2026

Each 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 assignment

Strings 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 lovelace

To 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

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

Searching

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 three

The 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

MethodReturnsExampleResult
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 4

The 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 passed

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: saturdays

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 c

The 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 x
  1. ord(letter) - ord("a") turns the letter into its place in the alphabet, from 0 for a to 25 for z.

  2. % 26 wraps past the end: for y, (24 + 3) % 26 is 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) % 26 is 23.

  3. 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 4

What 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 False

Emoji 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:

Common misconceptions

BeliefWhat Python doesExample that breaks it
A string’s first character is at index 1Indices start at 0"Python"[1] is "y"
The last index is the string’s lengthIt is the length minus 1"Python"[6] is an IndexError
A slice includes the character at its stopIt stops just before it"Python"[0:2] is "Py"
A method changes its stringIt returns a new stringAfter name.upper(), name is unchanged
One character of a string can be replacedStrings are immutableword[0] = "J" is a TypeError
find returns False when the text isn’t thereIt returns -1, which is also a valid indextext[text.find("x")] gives the last character
strip removes a word from the endsIt 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 seesIt counts code pointslen("👋🏽") is 2

Summary

Self-check

Answer each question before you open its answer.

  1. Given s = "notebook", what are s[2], s[-1], s[2:5], s[:4], and s[::-1]?

    Answer

    "t", "k", "teb", "note", and "koobeton". The slice s[2:5] has 5 − 2 = 3 characters, at indices 2, 3, and 4.

  2. 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, so name still has its three spaces. Only the call inside print uses a stripped copy.

  3. 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]}".

  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 than ord("a"), 97. Compare lowercase copies instead: "Zebra".lower() < "apple".lower() is False.

  5. The word “naïve” looks five characters long. Why can len give 5 for it in one program and 6 in another?

    Answer

    The ï can be one code point, U+00EF, or two: i followed by U+0308, the combining diaeresis. len counts code points, so the second form gives 6. unicodedata.normalize("NFC", text) turns the second form into the first.

Further reading