Sub topic 1
What a String Is: An Ordered Sequence of Characters
Prerequisites
This chapter assumes you can write loops and functions in any language. It also assumes you know zero-based indexing on arrays or lists, and basic Big-O notation such as O(1) and O(n). The examples use Python 3.
The working model
A string is an ordered sequence of characters. Two properties define it:
- Order matters.
"abc"and"cba"hold the same characters but are different strings. - Position matters. Each character sits at a numbered position, called an index, starting at 0.
Repeats are allowed, and the length is the number of positions. This is what separates a string from a set, which has no order and no repeats. It also separates a string from a general list, because a string's elements are all characters.
The sequence model gives you a small set of operations that nearly every language supports:
| Operation | Example | Result |
|---|---|---|
| Length | `len("hello")` | 5 |
| Index | `"hello"[1]` | `"e"` |
| Slice | `"hello"[1:4]` | `"ell"` |
| Concatenate | `"ab" + "cd"` | `"abcd"` |
| Compare | `"ab" == "ab"` | `True` |
| Search | `"abc" in "xabcx"` | `True` |
Later chapters look at what each operation costs. For now, the point is that they all follow from treating the text as a sequence.
Reading a string by position
Indexing returns one character. Slicing returns a new, shorter string. Python also accepts negative indexes, which count from the end.
s = "hello"
print(s[1]) # e
print(s[-1]) # o
print(s[1:4]) # ell
try:
s[0] = "J"
except TypeError:
print("strings are immutable")
t = "J" + s[1:]
print(t) # JelloA slice s[a:b] includes index a and stops before index b. The length of the result is b - a, which makes slices easy to reason about. s[1:4] has 3 characters.
The assignment s[0] = "J" fails. Python strings are immutable, meaning that once created, they cannot change. To get a changed string you build a new one, as t does. A later chapter explains why languages make this choice and what it costs.
Iterating over a string
Because a string is a sequence, you can loop over it directly:
def count_vowels(text):
total = 0
for ch in text:
if ch in "aeiou":
total += 1
return total
print(count_vowels("sequence")) # 4The loop visits each position in order, so the work grows in proportion to the length, which is O(n). Most whole-string operations, such as counting, copying, and comparing, take at least O(n) time in the worst case because they must look at every character.
What "character" hides
The word "character" looks simple, but it hides several different ideas. A user sees one symbol on screen. A programmer may mean a Unicode code point (a number assigned to a symbol), a byte in storage, or a user-perceived symbol made of several code points. Python's len counts code points, which matches the common idea of a character for many inputs but not for all.
s = "café"
print(len(s)) # 4 code points
print(len(s.encode("utf-8"))) # 5 bytesThe same text has length 4 or 5 depending on what you count. The next chapters separate these meanings: characters and code points, then encodings and bytes, then in-memory layout, and later grapheme clusters. Until then, keep one rule in mind: the sequence model is always correct, but you must know what one element of the sequence is.
Common errors
- Off-by-one in slices. The end index is excluded.
s[0:len(s)]gives the whole string, ands[0:len(s) - 1]drops the last character. - Mutating in place. Code like
s[i] = "x"works in some languages and fails in Python. Check your language's rules before relying on it. - Confusing characters with bytes.
lenof a string andlenof its encoded bytes can differ. - Index out of range.
s[5]on"hello"raisesIndexError. Valid indexes run from0tolen(s) - 1, or from-len(s)to-1.
Exercise
Given s = "sequence", what do s[2:5] and s[-3:] return, and how long is each result?
Show answer
s[2:5] returns "que" (indexes 2, 3, 4), with length 5 - 2 = 3. s[-3:] returns "nce" (the last three characters), with length 3.
Exercise
Write a Python function is_palindrome(text) that returns True if text reads the same forward and backward, using only slicing and comparison. What is its time cost for a string of length n?
Show answer
def is_palindrome(text): return text == text[::-1] The slice text[::-1] builds a reversed copy, which takes O(n) time and O(n) extra space, and the comparison takes O(n) time, so the total is O(n).