Lesson ยท Strings & Text
The str Type
51 min readThe str Type
`str` is an immutable sequence of Unicode code points as exposed through Python's text model. Treating strings as text rather than raw bytes is the foundation for correct internationalized programs.
Learning goals
- Describe a
stras an immutable sequence of Unicode code points and say where it sits relative to bytes. - Index and slice text with positive and negative positions and predict what each slice returns.
- Explain why
text.upper()produces a new string while the original name keeps its value. - Use concatenation, repetition, and iteration to build and walk text without assuming mutation.
- Predict which situations raise
TypeErrororIndexErrorbefore running the code.
Mental model
Indexing, slicing, and iteration all read the same sequence, and concatenation and repetition build new strings because nothing edits the original in place. Length and positions count code points rather than user-perceived characters, so a slice can split a character that a reader sees as one.
Read the sequence, build new text
nothing edits a string in place
Mental model
the same mechanism as a compact list
str: immutable sequence of Unicode code points โ read by position text[0], text[-1], text[0:6] (slices copy to a new string) โ walk the sequence for ch in text (one element per step) โ build new text "Py" + "thon", "ab" * 3 (originals never change)
Core idea
A str is a sequence of Unicode code points, which gives indexing, slicing, iteration, membership, and comparison a single uniform meaning, and it is immutable, which keeps strings safe to share and hash. Because every string operation returns a new string instead of editing the original, editing text is assembly rather than surgery, and code that reads like an in-place change is really building a replacement value. Immutability is also why strings can serve as dict keys while lists cannot.
Unicode strings
Python str represents Unicode text rather than encoded bytes. Indexing and length operate on Python's string elements, which are not always the same as user-perceived grapheme clusters.
Immutability
Immutability means the object's logical value cannot be modified in place through its public operations. New results are typically represented by new objects, although the object can still reference other mutable objects.
Indexing
Indexing selects an element by position. Positive indexes count from the front, negative indexes count from the end, and out-of-range element access raises IndexError.
Slicing
A slice copies a range of the sequence into a new string using text[start:stop:step], and all three parts are optional. The stop position is excluded, and out-of-range bounds clamp to the ends instead of raising, so text[2:100] returns everything from index 2 to the end.
Iteration
Iterating a string yields its elements one at a time, each a one-element string, in sequence order. for ch in text visits positions 0, 1, 2, and so on without manual counting, and it can only read the string, never modify it, because the sequence is immutable.
Concatenation
Concatenation joins two strings into a new string with +, leaving both operands unchanged. Only str values combine this way, so mixing in a number raises TypeError until it is converted, and concatenating in a loop creates one new string per step.
Repetition
Repetition text * n returns a new string containing n back-to-back copies of text, where n must be an integer and zero or negative counts produce an empty string. Like concatenation, it never changes the original, so building long text by repeating and extending allocates a new object at each step.
Membership
Membership uses in and not in to ask whether a value is present. The underlying cost depends on the container protocol and data structure, so list membership and set membership have very different performance profiles.
Comparison
Comparison in The str Type follows type-defined equality or ordering rules. Do not assume unrelated types can be ordered, and remember that equality is distinct from identity.
Walkthrough
len(text)counts sequence elements, so the snake emoji counts as one and the printed value is 8, not the number of bytes a UTF-8 file would store.text[0]selectsPfrom the front andtext[-1]selects the snake from the end, whiletext[0:6]copies out"Python"and leavestextexactly as it was."thon" in textanswers with a boolean, andupper = text.upper()binds a brand-new string; theprint(text)line afterwards still shows the lowercase letters.- Predict before running: each printed value, especially
len(text)and whether the finalprint(text)still shows lowercase letters.
Experiments to try
- Print
len("รฉ"),len("e\u0301"), and"รฉ" == "e\u0301"; the two visible forms differ in code point count and in equality. - Try
text[0] = "J"and read theTypeError, then produce the same result with"J" + text[1:]; no existing string changed, a new one appeared. - Iterate
for ch in textandprint(repr(ch)); every element is a one-character string, and the emoji arrives as a single element. - Print
text[::2]andtext[::-1]; then check thattext[99]raisesIndexErrorwhiletext[2:99]simply stops at the end.
Common mistakes
- Counting code points as user-perceived characters:
"รฉ"can be one code point or two (eplus a combining accent), solencan disagree with what a reader sees. - Treating strings as mutable:
text[0] = "J"raisesTypeErrorbecause no assignment into a string exists; the fix is to build a new string such as"J" + text[1:]. - Mixing text and numbers in an operation:
"1" + 1and"1" < 1raiseTypeErrorrather than guessing a conversion, which keeps"1"and1different values. - Assuming one element equals one visible character for emoji sequences: a flag or a skin-tone variant spans several code points, so indexing and slicing can split a character that renders as one.
Practice: Easy
- Work through the example in the REPL and print the type of
text,text[0], andtext[0:6]; confirm that indexing and slicing both returnstr. - Slice
"Python"out oftextfirst with positive indexes (text[0:6]) and then with negative ones (text[-8:-2]); check that both print the same characters. - Attempt
text[0] = "J", read the error, and then build"Jython ๐"with concatenation and a slice instead.
Practice: Medium
- Track what each operation does to
text:len, indexing, a slice,in,+, and*; record for every one whether it reads the sequence or creates a new string, and which exception it can raise. - Compare
"รฉ"and"e\u0301"with==,len, andrepr; explain which check matches the visible character and which one distinguishes the two spellings. - Evaluate
"ab" * 3 + "c"step by step and count how many new string objects the expression produces before the print; state why neither operand changes.
Practice: Hard
- Design a small text inspector for any input string: report the number of code points, the first and last elements, one slice, and whether a substring is present. Define the output for the empty string and one test before implementing.
- Build a failure lab with three cases: an out-of-range index, an item assignment, and an int-plus-string operation; explain what each error says about the
strcontract. - Connect this lesson to the encoding lesson: explain why
lenof astrcan differ from the number of bytes the same text occupies in UTF-8, and show a concrete character where the two numbers diverge.
Lesson checklist
- I can state that a
stris an immutable sequence of Unicode code points and what that implies for sharing and dict keys. - I can slice text with positive and negative indexes and say exactly which elements each slice keeps.
- I can explain why
.upper()returns a new string and the original stays unchanged. - I can give one concrete case where a code point and a user-perceived character disagree.
Remember
A `str` is an immutable sequence of Unicode code points: indexing, slicing, iteration, membership, and comparison read it by position, while concatenation, repetition, and every case method build new strings rather than editing the original. Length and positions count code points, which is why one visible character can span several of them, and immutability is what makes strings safe to share and use as dict keys.
Interview angles
What is the main purpose of **Unicode strings**?+
Python str represents Unicode text rather than encoded bytes. Indexing and length operate on Python's string elements, which are not always the same as user-perceived grapheme clusters.
What should you pay attention to when using **Immutability**?+
Immutability means the object's logical value cannot be modified in place through its public operations. New results are typically represented by new objects, although the object can still reference other mutable objects.
How does **Indexing** fit into this lesson?+
Indexing selects an element by position. Positive indexes count from the front, negative indexes count from the end, and out-of-range element access raises IndexError.
Why does `text[0] = "J"` raise, and what do you write instead?+
A str is immutable, so it supports no item assignment and the statement raises TypeError. Build a new string from the pieces, for example "J" + text[1:], and bind it to a name; the original text is never modified.