Strings are sequences, not magic
Clean, slice, search and format text without losing information.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners building Python foundations; revisit the preparation topics whenever the vocabulary is unfamiliar.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 12 minutes; optional deep dive: 8 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Index and slice text
- Use immutable transformations
- Format readable output
Read positions and ranges
A string is an ordered, immutable sequence of Unicode code points. An index selects one position; a slice selects a range.
Understand first
Text often contains a prefix, a suffix or a short excerpt. Knowing the exact position rule prevents missing or extra characters.
Words you will see
- Index
- A zero-based position in a sequence.
- Slice
- A range written with a colon; its stop is excluded.
- Immutable
- Not editable in place after creation.
Read the positions before slicing
The positions in python are p at 0, y at 1, t at 2, h at 3, o at 4 and n at 5. word[0] selects p. word[-1] selects the last code point, n. Negative indexes count backward from the end; they do not reverse the text.
word[1:4] includes positions 1, 2 and 3, giving yth. The stop position 4 is not included. Omitting a start uses the beginning and omitting a stop uses the end. Half-open ranges make adjacent slices fit together without duplicating their boundary.
Choose safe bounds deliberately
An out-of-range single index raises IndexError. Indexing an empty string therefore fails. A slice clamps its bounds, so text[:3] works for empty and short text as well as long text. Choose slicing for a preview that may be shorter than its requested length.
Assigning word[0] = 'P' raises TypeError because strings are immutable. Build another string if you want changed text. A slice selects code points, not necessarily whole visible characters; the optional Unicode section explains that boundary.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
word = "python"Bind a six-code-point string.
print(word[0], word[-1])Select the first and last positions and print them with a space.
print(word[1:4])Select y, t and h; position 4 is excluded.
A string is an immutable sequence of Unicode code points. Indexing starts at 0; a slice includes its start and excludes its stop. Negative indexes count backward. An out-of-range index raises IndexError; a slice clamps its bounds.
Conceptual positions and an excluded stop
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- Positionsp:0, y:1, t:2, h:3, o:4, n:5
- Select [1:4]Start at y; include positions while they are less than 4.
- Resultyth is new text; the source remains python.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Move the stop boundary.
Try: Change word[1:4] to word[1:5].
The slice becomes ytho, adding the previous stop position.
Compare clamping with indexing.
Try: Add print(word[:99]), then print(word[99]).
The slice prints python; the subsequent index raises IndexError.
Before you move on
For 'lamp', what do text[:2] and text[2:] return? Is any position repeated?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
They return 'la' and 'mp'. The first slice excludes position 2 and the second starts there, so the pieces have no overlap.
Transformations return new strings
String transformations return results rather than changing the source. A chain feeds each result into the next operation.
Understand first
Normalising a tag creates a consistent search or URL label while keeping the original text for display or review.
Words you will see
- strip
- Return text without leading and trailing whitespace.
- split
- Break text into a list of parts; without an argument, use runs of whitespace.
- join
- Combine string parts using the string before .join as a separator.
Follow the value through the chain
raw begins with two spaces, mixed case and two trailing spaces. strip removes only the outer whitespace. lower returns lowercase text. split without an argument separates whitespace-delimited words and ignores leading/trailing whitespace. It returns ['python', 'basics'].
The separator "-" joins those words into python-basics. The separator goes between parts, not at either end. Every operation receives the previous result. The original raw binding still reaches the original string, so raw.startswith(" ") remains True.
Normalisation is a policy choice
This policy merges runs of whitespace into one hyphen and lowercases text. It does not remove punctuation or guarantee a unique identifier: different inputs can produce the same tag. Keep the original value if that distinction matters.
Empty or whitespace-only text splits into an empty list, and joining it returns an empty string. Decide separately whether an empty tag is allowed. Use split(',') for a literal comma delimiter, but use csv for quoted CSV fields; a simple split is not a full file-format parser.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
raw = " Python Basics "Keep the original padded text.
tag = "-".join(raw.strip().lower().split())Strip, lowercase, split words and join them with one hyphen.
print(tag)Display the transformed text.
print(raw.startswith(" "))Confirm the source still starts with its original spaces.
strip, lower and replace return strings rather than editing the original. Assign the result if you need it later. Use split to parse a simple delimiter and join to build text from pieces.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Collapse internal whitespace.
Try: Change raw to " Python Basics ".
The tag is still python-basics because split groups whitespace.
Use another separator.
Try: Change "-".join to "_".join.
The tag becomes python_basics; source preservation is unchanged.
Before you move on
What tag results from ' DATA Notes ', and are the three inner spaces preserved?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
The result is 'data-notes'. split without an argument treats the whitespace run as a separator, and join inserts one hyphen. The source itself is unchanged.
Use readable interpolation
An f-string builds text by inserting expression results between fixed words. The resulting message is data, not an instruction to another system.
Understand first
Application messages need readable labels and values. Keeping presentation separate from computation makes the intended wording easy to check.
Words you will see
- Interpolation
- Inserting values into text.
- f-string
- A string prefixed with f whose braces contain expressions.
- Format specification
- Optional instructions after a colon inside braces that control the display.
Read fixed text and inserted values separately
The f before the opening quote enables interpolation. In f'{name}: {count}', name and count are read as Python expressions. The colon and space outside the braces are ordinary characters in the resulting message. count stays an integer; producing text does not change it.
The second print uses {price:.2f} to display two digits after the decimal point. It gives a display of 2.50 rather than changing the stored float into a decimal-accounting type. Exact output formatting and numerical correctness are different concerns.
Do not turn user text into code
Use f-strings for messages, labels and reports. Use the database driver's parameter mechanism for SQL values, not an interpolated SQL command. Likewise, passing a formatted string to a shell can make data become executable instructions.
An empty name inserts empty text; the fixed punctuation still appears. If that wording is undesirable, validate or choose a separate empty-name message explicitly. A missing variable raises NameError rather than inserting a blank automatically.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
name = "Mira"Supply the label value.
print(f"{name}: {count}")Insert Mira and 3 around fixed punctuation.
print(f"Unit price: {price:.2f}")Format the price for display with two decimal places.
Use f-strings for application messages, such as f'{name}: {count}'. They are not a safe replacement for parameterised SQL. Keep user input as data rather than inserting it into executable commands.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Observe a zero count.
Try: Change count = 3 to count = 0.
The first line becomes Mira: 0.
Keep expressions explicit.
Try: Add print(f"Next count: {count + 1}").
It displays 4 for the original count, but count remains 3.
Before you move on
If count becomes 0, does f'{name}: {count}' omit it?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. It inserts the numeric value as '0', producing 'Mira: 0'. Interpolation does not treat zero as absent.
Where this idea earns its place
Text processing starts with the distinction between text and encoded bytes. A str models Unicode code points; bytes models raw byte values. A file encoding or network charset defines conversion between them. The length of a string therefore need not equal its UTF-8 byte length or the number of characters a person perceives on a screen.
Follow the mechanism step by step
Indexing selects a code point by position; slicing constructs a selected sequence using start-inclusive, stop-exclusive bounds. Methods such as strip and replace return values because strings are immutable. When a pipeline applies raw.strip().lower().split(), each stage has a distinct input and result; record those intermediate values while learning rather than treating the chain as magic.
Work through a concrete application
Normalise a simple tag by removing boundary whitespace, splitting runs of whitespace and joining tokens with a hyphen. Test what happens to an empty input, repeated spaces and punctuation. Then decide whether a tag should preserve case or use a broader caseless comparison. Do not apply lowercasing to identifiers, passwords or display names without a domain rule.
Failure cases and misleading shortcuts
split(',') is not a CSV parser, and replacing a few characters is not SQL parameterisation or HTML escaping. Different output contexts require different handling. Also distinguish strip, which removes selected boundary characters, from removing an exact prefix. Unicode normalisation can be relevant when canonically equivalent spellings must compare consistently.
Cost, ownership and alternatives
A k-character slice generally allocates O(k) output space and copying work. Building a long string by repeated concatenation can repeatedly copy growing content; collecting fragments and joining expresses the intended batch construction. Unicode representation details depend on the implementation, so do not equate one code point with one fixed byte of memory.
Verify the contract
Test empty text, missing search terms, non-ASCII input, combining marks, an oversized input and the exact boundary rule for trimming. Compare decoded values separately from encoded payloads. If a field has a size limit, state whether it limits code points, grapheme clusters or bytes; otherwise different layers can accept and reject the same input inconsistently.
Transfer question: A service limits a field to 20 characters but a database rejects its encoded size. What contract is missing?
The layers disagree about what length measures. Specify the encoding and whether the limit is in bytes or text units, then validate at the boundary that owns that limit. Avoid blindly truncating encoded bytes, which can split a multibyte sequence and produce invalid text.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Clean a label
Remove surrounding whitespace and convert the label to lowercase.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided: return a normalised tag
Collapse whitespace, lowercase words and join them with hyphens.
The contract
- raw is a string; no external input or packages are needed.
- Return lowercase whitespace-separated words joined with one hyphen. Preserve punctuation and repeated words.
- Empty or whitespace-only text returns ''. The original text stays unchanged.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- padded title
from copy import deepcopy args = (" Python Basics ",) before = deepcopy(args) expected = "python-basics" result = normalise_tag(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for padded title" assert args == before, "Preserve every supplied input" - empty text
from copy import deepcopy args = ("",) before = deepcopy(args) expected = "" result = normalise_tag(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for empty text" assert args == before, "Preserve every supplied input" - only whitespace
from copy import deepcopy args = (" \t\n ",) before = deepcopy(args) expected = "" result = normalise_tag(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for only whitespace" assert args == before, "Preserve every supplied input" - internal whitespace
from copy import deepcopy args = ("Data Notes\tNow",) before = deepcopy(args) expected = "data-notes-now" result = normalise_tag(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for internal whitespace" assert args == before, "Preserve every supplied input" - repeated words
from copy import deepcopy args = ("Go Go",) before = deepcopy(args) expected = "go-go" result = normalise_tag(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for repeated words" assert args == before, "Preserve every supplied input" - keep punctuation
from copy import deepcopy args = (" A+B! ",) before = deepcopy(args) expected = "a+b!" result = normalise_tag(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for keep punctuation" assert args == before, "Preserve every supplied input"
Does this produce a unique safe identifier for every input?
No. Different whitespace and case variants intentionally merge, and punctuation stays. It processes n code points with linear-size intermediate and output storage.
Guided: select a safe preview
Take up to a requested number of code points without indexing failures.
The contract
- text is a string and limit is a nonnegative integer.
- Return text's first limit code points. A shorter source returns in full; zero limit returns ''.
- No ellipsis, trimming or mutation. This is not a whole-visible-character guarantee.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- short preview
from copy import deepcopy args = ("python", 3) before = deepcopy(args) expected = "pyt" result = text_preview(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for short preview" assert args == before, "Preserve every supplied input" - zero limit
from copy import deepcopy args = ("python", 0) before = deepcopy(args) expected = "" result = text_preview(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for zero limit" assert args == before, "Preserve every supplied input" - empty source
from copy import deepcopy args = ("", 4) before = deepcopy(args) expected = "" result = text_preview(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for empty source" assert args == before, "Preserve every supplied input" - overlong limit
from copy import deepcopy args = ("cat", 20) before = deepcopy(args) expected = "cat" result = text_preview(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for overlong limit" assert args == before, "Preserve every supplied input" - exact length
from copy import deepcopy args = ("lamp", 4) before = deepcopy(args) expected = "lamp" result = text_preview(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for exact length" assert args == before, "Preserve every supplied input" - preserve spaces
from copy import deepcopy args = (" a b ", 3) before = deepcopy(args) expected = " a " result = text_preview(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for preserve spaces" assert args == before, "Preserve every supplied input"
Why is text[limit] the wrong operation?
It selects one code point and may fail, rather than producing a bounded prefix. Producing a k-code-point slice generally needs O(k) output space and work.
Transfer: match without losing original labels
Search with a Unicode-aware normalisation key but return untouched labels.
The contract
- labels is a list of strings and query is a string.
- Match whole labels after strip().casefold() on each label and query, not substring matching.
- Return a new list of original labels in source order, preserving duplicates and original padding/case. Empty query can match whitespace-only labels; inputs remain unchanged.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- padding and case
from copy import deepcopy args = ([" Tea ", "rice", "TEA"], "tea") before = deepcopy(args) expected = [" Tea ", "TEA"] result = label_matches(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for padding and case" assert args == before, "Preserve every supplied input" assert result is not args[0] and all(type(label) is str for label in result), "Respect nested types and ownership promises"
- empty list
from copy import deepcopy args = ([], "tea") before = deepcopy(args) expected = [] result = label_matches(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for empty list" assert args == before, "Preserve every supplied input" assert result is not args[0] and all(type(label) is str for label in result), "Respect nested types and ownership promises"
- Unicode fold
from copy import deepcopy args = (["Straße", "STRASSE", "road"], "strasse") before = deepcopy(args) expected = ["Straße", "STRASSE"] result = label_matches(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for Unicode fold" assert args == before, "Preserve every supplied input" assert result is not args[0] and all(type(label) is str for label in result), "Respect nested types and ownership promises"
- not substring
from copy import deepcopy args = (["teapot", "tea"], "tea") before = deepcopy(args) expected = ["tea"] result = label_matches(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for not substring" assert args == before, "Preserve every supplied input" assert result is not args[0] and all(type(label) is str for label in result), "Respect nested types and ownership promises"
- repeated matches
from copy import deepcopy args = (["x", "x", "y"], " X ") before = deepcopy(args) expected = ["x", "x"] result = label_matches(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for repeated matches" assert args == before, "Preserve every supplied input" assert result is not args[0] and all(type(label) is str for label in result), "Respect nested types and ownership promises"
- empty key
from copy import deepcopy args = (["", " ", "x"], "") before = deepcopy(args) expected = ["", " "] result = label_matches(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for empty key" assert args == before, "Preserve every supplied input" assert result is not args[0] and all(type(label) is str for label in result), "Respect nested types and ownership promises"
Why not return a set of folded labels?
It would discard duplicates, source order and original presentation, violating the changed contract. Work scans the total text length; output storage grows with the number of matches.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestoneHuman characters can span code points
Unicode code points, visible characters and encoded bytes are different units. Python string length measures code points.
Understand first
A UI limit, a cursor position and a network message size can need different measurements. Counting the wrong unit can cut visible text in an unexpected place.
Words you will see
- Code point
- A numbered Unicode text element represented in a Python string.
- Combining mark
- A code point that can combine visually with another, such as an accent.
- Encoding
- A rule for representing text as bytes, such as UTF-8.
One visible accent, two representations
composed uses the single code point for é. combined uses e followed by a combining acute accent. They may look the same, but their lengths are 1 and 2, and ordinary string equality is False because the sequences differ.
Encoding the composed character as UTF-8 produces two bytes, so the third print is 2. Unicode normalisation with NFC converts this decomposed sequence to the composed form, making the final comparison True. Normalisation is an explicit operation, not an automatic property of ==.
Match the unit to the task
Use len(text) for code-point counts and len(text.encode('utf-8')) for UTF-8 byte counts. Neither is a general visible-character count: emoji sequences can combine many code points. Robust cursor movement needs appropriate grapheme-boundary handling beyond simple indexing.
Decode bytes using the known encoding and an intentional error policy. Silently ignoring invalid bytes loses information. Normalisation can help with consistent comparison, but it does not make all visually similar strings equivalent or solve security-sensitive identifier policy on its own.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
combined = "e\u0301"Write e plus a separate accent code point.
print(len(composed), len(combined))Count one versus two code points.
print(len(composed.encode("utf-8")))Count two encoded bytes for the single composed code point.
print(unicodedata.normalize("NFC", combined) == composed)Compare after an explicit normalisation step.
len measures code points, not user-perceived characters or encoded bytes. Combining marks and emoji sequences complicate cursor movement and limits. Encoding to UTF-8 produces bytes; decoding requires the appropriate encoding and error policy.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Try ASCII.
Try: Set composed = "A" and combined = "A".
Lengths are 1 and 1, equality is True and the byte count is 1.
Inspect a sliced sequence.
Try: Add print(len(combined[:1])).
It prints 1, but that slice includes only e and excludes the separate accent.
Before you move on
If text is one ASCII letter 'A', do its code-point count and UTF-8 byte count differ?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. Both are 1 for that input. Agreement on ASCII does not establish that the units agree for all Unicode text.
Build text once
Joining combines a sequence of strings with a separator. Case folding produces text intended for broad Unicode caseless comparison.
Understand first
Reports need predictable separators, while search may need to recognise case variants beyond ASCII. These are separate text transformations with different policies.
Words you will see
- Fragment
- One piece of text to be assembled.
- casefold
- A Unicode-oriented transformation for caseless matching.
- Output size
- The number of code points or bytes in the produced result; name the chosen unit.
Build an intentional result
The fragments north, east and west are joined with ' | ' between them. The original list is not edited. A one-element list needs no separator, and joining an empty list gives an empty string. All fragments must be strings; join does not silently convert arbitrary numbers.
The second line compares Straße and STRASSE after casefold. The German sharp s folds to ss, so these compare equal. lower is sufficient for some policies but does not perform that particular expansion; pick the transformation that matches the search requirement.
Reason about copying without folklore
When building many fragments, collecting them and joining avoids expressing the job as repeated growth of an immutable string. Repeated concatenation can repeatedly copy an expanding prefix; implementation optimisations exist, so do not claim every use of + is always slow.
For total output length k, assembling the result requires work and storage proportional to that output, with additional bookkeeping for fragments. Case folding can change length and is not locale-specific user sorting. Keep the original labels when returning search results rather than displaying only their folded keys.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
parts = ["north", "east", "west"]Keep three ordered fragments.
print(" | ".join(parts))Insert the separator only between neighboring fragments.
print("Straße".casefold() == "STRASSE".casefold())Compare the folded forms, not their original spellings.
Repeated concatenation may cause repeated copying; collect pieces and join when building many fragments. Slicing k characters generally allocates O(k) output space. Choose casefold rather than lower for broader Unicode caseless matching.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Remove every fragment.
Try: Change parts to [].
The first print emits an empty line.
Compare a narrower policy.
Try: Replace both casefold calls with lower calls.
The second print becomes False because lower does not turn ß into ss.
Before you move on
What does ','.join(['only']) return, and why is there no trailing comma?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
It returns 'only'. A separator joins neighboring pieces; with one piece there is no gap to fill.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.