Sub topic 1
Strings as ordered sequences
A Python string is a sequence: a fixed collection of items in a definite order. Once you see strings this way, indexing, slicing, iteration and len() all follow from one model. This chapter builds that model. Later chapters use it to read single characters and cut out slices.
Prerequisites
This chapter assumes you can:
- Run Python code in a REPL or a script.
- Write a string literal and assign it to a variable.
- Use
print()andlen(). - Read a simple
try/exceptblock.
You don't need to know anything about indexes or slices yet.
What "sequence" means in Python
A sequence is an object that holds items in a fixed order, where each item has a numbered position. Python's built-in sequence types include str, list, tuple, range and bytes. They share a set of operations:
len(x)returns the number of items.for item in xvisits the items from first to last.item in xtests whether something is present.x[i]reads the item at positioni.x[a:b]produces a part of the sequence.x + yandx * nbuild new sequences by joining and repeating.x.index(item)andx.count(item)search the sequence.
A str supports all of these. The item type is what differs. In a list the items can be anything. In a string every item is itself a string of length 1.
s = "Python"
print(type(s))
print(len(s))
print(type(s[0]))
print(s[0] == "P")The output is:
<class 'str'>
6
<class 'str'>
TruePython has no separate "character" type. A single character is just a string whose length is 1. That has a surprising consequence: indexing a one-character string gives you back an equal string.
print("P"[0][0][0])This prints P.
The order is part of the value
Two strings with the same letters in a different order are different values. Order is part of what a string is.
print("abc" == "cba")
print(sorted("abc") == sorted("cba"))
print("listen" == "silent")
print(sorted("listen") == sorted("silent"))This prints False, True, False, True. Sorting both strings into the same order is how you ignore order when you want to. This trick underlies simple anagram checks.
The positions in a string are numbered, and the diagram shows the layout for "Python". The numbering rules are the subject of the next two chapters. Here, notice only that the characters sit in a line and each has a place.
Operations every sequence shares
Length and iteration
len() counts the items. A for loop visits them in order, from the first to the last.
s = "Python"
print(len(s))
for ch in s:
print(ch, end=" ")
print()The loop prints P y t h o n . When you need the position as well as the character, use enumerate(). It pairs each item with a counter.
s = "Python"
for position, ch in enumerate(s):
print(position, ch)This prints six lines, from 0 P to 5 n. Counting starts at 0. The next chapter explains why.
The empty string "" is a sequence with no items. Its length is 0 and it is falsy, so if text: is a common way to test that a string is not empty.
print(len(""))
print(bool(""))
print(bool(" "))This prints 0, False and True. A string containing only a space has one item, so it is truthy.
Membership
The in operator tests whether something occurs in the string. For strings, it works on substrings, not only single characters. That is a difference from lists, where in tests for a single item.
s = "Python"
print("t" in s)
print("th" in s)
print("ty" in s)
print("" in s)
print("p" in s)This prints True, True, False, True, False. Two points are worth remembering:
- A substring must appear contiguously and in the same order, so
"ty"is not found. - The empty string is a substring of every string.
Matching is case-sensitive, so "p" is not in "Python".
Searching: index and count
s.index(sub) returns the position where sub first appears. If sub is missing, it raises ValueError. s.count(sub) returns the number of non-overlapping occurrences. s.find(sub) is a variant of index that returns -1 instead of raising.
s = "banana"
print(s.index("n"))
print(s.count("an"))
print(s.find("x"))
try:
s.index("x")
except ValueError as e:
print(e)The output is:
2
2
-1
substring not foundJoining, repeating and comparing
+ and * build new strings. They never change an existing one.
a = "Py"
b = "thon"
print(a + b)
print(a * 3)
print("-" * 10)This prints Python, PyPyPy and ten hyphens.
Strings also compare in order. Python compares them one item at a time, using each character's Unicode code point number. Code point numbers are the integers Unicode assigns to characters. The first position where the two strings differ decides the result.
print(ord("P"), ord("p"))
print("Python" < "python")
print("apple" < "apricot")
print("app" < "apple")This prints 80 112, then True, True, True. Uppercase letters come before lowercase ones because their code points are smaller. A string that is a prefix of another string is smaller.
Strings versus other sequences
All sequences share the operations above, but they differ in what they contain and whether they can change.
| Type | Items | Can change in place? | Example |
|---|---|---|---|
| `str` | one-character strings | No | `"abc"` |
| `list` | any objects | Yes | `["a", "b", "c"]` |
| `tuple` | any objects | No | `("a", "b", "c")` |
| `range` | integers | No | `range(3)` |
| `bytes` | integers from 0 to 255 | No | `b"abc"` |
You can check membership in the sequence family with the standard library.
from collections.abc import Sequence
print(isinstance("abc", Sequence))
print(isinstance([1, 2], Sequence))
print(isinstance({1, 2}, Sequence))
print(isinstance({"a": 1}, Sequence))This prints True, True, False, False. Sets and dictionaries are collections, but they are not sequences in this sense. Sets have no positions. Dictionaries have insertion order, but their keys are not positions in a sequence.
bytes is the one most often confused with str. Their items are different types.
print("abc"[0])
print(b"abc"[0])This prints a and then 97. Indexing a str gives a string. Indexing bytes gives an integer.
Common mistakes
Most errors with string sequences come from forgetting what the items are.
- Expecting words. Iterating a string gives characters, not words. To get words, call
.split(). - Expecting numbers. The items of
"123"are the strings"1","2"and"3". They are not integers, sosum("123")raisesTypeError. Convert first withint(). - Treating a string as a list you can edit. Strings are immutable, so item assignment fails. A later chapter in this tutorial covers this in detail.
- Assuming
len()counts what you see. It counts code points, which can differ from the visible characters.
Here is the second mistake, with the fix.
digits = "123"
print(list(digits))
print(sum(int(d) for d in digits))
try:
sum(digits)
except TypeError as e:
print(e)The output is:
['1', '2', '3']
6
unsupported operand type(s) for +: 'int' and 'str'What the items really are
The items of a Python string are Unicode code points. A code point is a number that Unicode assigns to one character or symbol. ord() converts a one-character string to its code point and chr() converts back.
print(ord("P"))
print(chr(80))
print(ord("é"))
print(len("naïve"))This prints 80, P, 233 and 5. In most everyday text, one code point corresponds to one visible character. That is why the sequence model matches your intuition most of the time.
It breaks down in a few cases. Some visible characters are built from several code points. For example, "e" followed by a combining accent looks like one letter, but it counts as two items.
composed = "caf\u00e9"
decomposed = "cafe\u0301"
print(composed, decomposed)
print(len(composed), len(decomposed))
print(composed == decomposed)The two strings look the same when printed, but they have lengths 4 and 5, and they are not equal. Python does not hide this: every index, slice and len() call works on code points. A later chapter returns to this edge case.
Putting it together
This function uses only sequence operations: iteration, membership and len(). It counts the vowels in a string.
def count_vowels(text):
vowels = "aeiou"
total = 0
for ch in text.lower():
if ch in vowels:
total += 1
return total
print(count_vowels("Python"))
print(count_vowels("Sequence"))
print(count_vowels(""))This prints 1, 4 and 0. The loop treats text as a sequence of one-character strings. The test ch in vowels uses membership on another string. Notice that vowels is itself a sequence, so the same idea appears twice. The .lower() call returns a new string, and the original text stays unchanged.
Exercise
What does each of these expressions print: len("a b"), "b a" in "a b a", and list("hi")? Explain why "ab" in "a b" gives a different answer from "a" in "a b" and "b" in "a b".
Show answer
len("a b") prints 3, because the space is an item. "b a" in "a b a" prints True, because the substring "b a" appears contiguously at the end. list("hi") prints ['h', 'i']. For the explanation: "ab" in "a b" is False because the substring test needs the characters side by side, and the space separates them. The version with and tests each character on its own, so it is True.
Exercise
Write a function digit_total(text) that returns the sum of the digits that appear in text, ignoring everything else. For example, digit_total("a1b22") returns 5. Which sequence operations does it use?
Show answer
One solution is def digit_total(text): return sum(int(ch) for ch in text if ch in "0123456789"). It uses iteration over the string, membership with in to filter out non-digits, and int() to convert each one-character string to a number. The conversion is needed because the items of a string are strings, not integers. digit_total("a1b22") returns 1 + 2 + 2 = 5.