University of Free Knowledge
QA 76.73 · fol. 14

A Sequence of Characters

A string is an immutable indexed sequence of characters you can slice, search, and rebuild into new strings. · 11 min

You have printed strings and read them from input since the first program. Now look inside one. A string is text stored as a sequence of characters in order — much like a list, but of letters, digits, and spaces. Because it is a sequence, you can reach any character by its index and pull out a run of characters called a slice. One difference sets strings apart from lists: a string cannot be changed once made. To transform text, you build a new string from the old one. Reach in, cut out a piece, search it, rebuild it — that is the work of this folio.

Guess before you learn

A string is indexed like a list: `` s = 'PYTHON' ` What is s[0]`?

THE DEPTH DIAL — the same idea, younger or deeper
9–12

9–12

A string is an immutable, index-addressed sequence of characters. Indexing is zero-based, with negatives counting from the end: for s = 'PYTHON', s[0] is 'P' and s[-1] is 'N'. A slice s[a:b] returns the characters from index a up to but not including b, so s[2:5] is 'THO'; omit an end to run to the edge (s[:3], s[3:]). Immutability means no character can be reassigned — s[0] = 'J' raises a TypeError. Every transforming operation instead returns a new string: s.upper(), s.replace('O', '0'), and s + '!' all leave s untouched and hand back fresh text you can name and reuse.

slice

A run of characters copied out of a string by a range of indices. s[a:b] takes index a up to but not including b.

INDEX01234character'H''E''L''L''O'from the end-5-4-3-2-1
PLATE I Each character of 'HELLO' sits at a position — from 0 at the front, or from -1 at the back.

Reading one character uses an index, just like a list: s[0] is the first, s[-1] the last. A slice copies several at once. Write two indices with a colon between them: s[1:4] takes the characters at 1, 2, and 3 — and stops before 4. The stop index is not included, which is the same fencepost rule you met with range(). Leave a side blank to run to the edge: s[:3] is the first three characters, s[3:] is everything from index 3 onward. And len(s) counts the characters.

Slice and measure s = 'PYTHON' — the steps fade as you master them

1
Indexing starts at 0. What single character is s[0]?
s[0]
2
A slice stops before its second index. What is s[0:3] — indices 0, 1, 2?
s[0:3]
3
Leaving the end blank runs to the finish. What is s[2:]?
s[2:]
4
A negative index counts from the back. What is s[-1]?
s[-1]
5
len counts the characters. What is len(s)?
len(s)
Retrieval Gate — answer before you continue 0 / 4

1.For s = 'code', what is s[1]?

2.For s = 'ARCHIVE', what is s[0:4]?

3.What is len('python')?

4.For s = 'GRID', what is s[-1]?

Now the trait that makes strings different from lists: a string is immutable. You cannot reassign one of its characters. Writing s[0] = 'J' does not edit the text — it raises a TypeError. So every operation that seems to change a string actually returns a new string and leaves the original alone. s.upper() hands back an upper-case copy; s.replace('a', 'o') hands back a copy with the swaps made; s + '!' joins two strings into a third. If you want to keep the result, you must store it — often back in the same name, with s = s.upper().

Why is this true?

Why does s = 'cat' followed by s.upper() still leave s as 'cat'?

Because a string is immutable, upper() cannot change s in place; it returns a new string 'CAT' and leaves the original untouched. Unless you store that result — s = s.upper() — the new string is computed and then discarded.

OPERATIONEXAMPLERETURNSone characters[0]'P'a slices[1:4]'YTH'how manylen(s)6contains?'TH' in sTrueupper-case copys.upper()'PYTHON'joineds + '!''PYTHON!'
PLATE II Everyday string operations on s = 'PYTHON'. Each returns a value; none changes s.

Searching a string is common enough to have its own word: the in operator. 'TH' in 'PYTHON' is True because those characters appear in order; 'Z' in 'PYTHON' is False. Since a string is a sequence, a for loop walks it one character at a time: for ch in s: binds ch to each character in turn. That is how you rebuild text — loop across the old string, decide what each character becomes, and add the pieces onto a new string you are growing.

Ink That Thinks — guess first; the answer draws itself.
You want to build an upper-case copy of a word by looping over it. Drag these steps into a workable order.

  1. start with an empty string to collect the result
  2. loop over each character of the original word
  3. add the upper-case form of the character onto the result
  4. after the loop, the result holds the finished new string
Reorder, then commit.
PLATE III Rebuilding a string is construction, not editing — guess in graphite, truth in ink.
Retrieval Gate — answer before you continue 0 / 4

1.What happens when this runs? `` s = 'cat' s[0] = 'b' ``

2.What does this print? `` s = 'go' s.upper() print(s) ``

3.What is 'un' in 'unhappy'?

4.In one sentence, why must you write s = s.upper() rather than just s.upper() if you want s to become upper-case?

A string, then, is a list-like sequence of characters you can index and slice, search with in, and walk with a loop — but never edit in place. To change text is to build new text. With lists holding many values and strings holding text, you have the two collections most programs scan. The next folio puts a loop to work on them: one pass across a sequence, carrying a single memory variable, is enough to find the largest value, count the matches, or search for one.

Practice — new ink and old, interleaved

1.Without looking back: what does a for loop do each pass, and what does range(n) produce?

2.x is 3. if x > 5: print('a') / elif x > 1: print('b') / else: print('c'). What is printed?

3.What prints? `` s = 'hi' if len(s) == 2: print('short') else: print('long') ``

4.For nums = [11, 22, 33], what is nums[-1]?

5.Why does age = input() followed by print(age + 1) cause an error?

6.name = input() and the person types 42. What type is name?

7.How many times does the body run? `` count = 0 for ch in 'code': count = count + 1 print(count) ``

8.Review from folio 2: what is the type of "7", written with quotes?

9.What is len('archive')?

10.For s = 'MARBLE', what is s[2:5]?

The Call Slip — search everything Ctrl·K / ⌘K