05 / 22 · Getting Started
Strings and text
Text in Python: a str as an immutable sequence of Unicode code points, encodings and UTF-8 bytes, indexing and slicing, the common string methods, f-strings with format specifications, the template strings of Python 3.14, and the first steps of text processing for NLP.
On this page 9
The previous note finished the skeleton of a program: values, names, control flow and functions. Almost every program also reads or writes text: file names, messages, tables of results, and in the NLP courses the data itself. Text looks simple and is not. A letter can take one byte in a file or four; two strings that look identical can compare unequal; and building a message by gluing strings together is how programs get injection bugs. This note states what a Python string is, how it becomes bytes and back, how to cut and clean it, and how to put values into it safely, with f-strings and with the template strings that are new in Python 3.14.
Notation. A code point is the number that Unicode assigns to a character, written U+ followed by at least four hexadecimal digits: U+0041 is A, U+20AC is €. A byte is written as two hexadecimal digits, as in E2.
Baseline: text as bytes#
Underneath, every file, every network message and every string in memory is a sequence of bytes, numbers from 0 to 255. The oldest convention, ASCII, gives each of 128 characters one byte, so that for English text “one character, one byte” holds and a string can be treated as an array of bytes (Bits, integers and byte order). That fails at the first é or € or кот: there are far more than 256 characters, so most must take several bytes, and an array of bytes no longer has one element per character. Counting, indexing and reversing bytes then cuts characters in half.
A string is a sequence of code points#
>>> s = "naïve €"
>>> len(s)
7
>>> [hex(ord(c)) for c in s]
['0x6e', '0x61', '0xef', '0x76', '0x65', '0x20', '0x20ac']
>>> s[2], ord(s[2]), chr(239)
('ï', 239, 'ï')
>>> b = s.encode("utf-8")
>>> b
b'na\xc3\xafve \xe2\x82\xac'
>>> len(b), type(b)
(10, <class 'bytes'>)
>>> b.decode("utf-8") == s
True
Line by line: the string has seven code points, including the space. ord gives the code point of a one-character string and chr goes back; the ï is code point 239, U+00EF. encode("utf-8") produces a bytes object of ten bytes. Its display shows printable ASCII bytes as characters and every other byte as \x and two hexadecimal digits: ï became the two bytes C3 AF and € the three bytes E2 82 AC. Decoding the bytes with the same encoding gives back the same string.
A string as code points and as UTF-8 bytes
- The string holds seven characters.
- Each is a code point, a number.
- Indices count code points, from 0 at the start and from −1 at the end.
- UTF-8 stores each code point in one to four bytes: one for ASCII, two for most Latin letters with accents and for Cyrillic, three for most other characters in common use, such as
€and Chinese characters, four for emoji. - So the two lengths differ: 7 code points, 10 bytes.
UTF-8, in one rule. The first byte of a character says how many bytes follow, and every following byte starts with the bits 10; the table and a worked example are in the ACOS course. Two consequences matter in practice. ASCII text is valid UTF-8 unchanged. And a sequence of bytes cut in the middle of a character is not valid UTF-8, which is what the most common decoding error says:
>>> "€".encode("utf-8")[:2].decode("utf-8")
Traceback (most recent call last):
...
UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 0-1: unexpected end of data
str and bytes do not mix. They are different types, and Python refuses to guess an encoding between them:
>>> data = b"abc"
>>> data[0], type(data[0])
(97, <class 'int'>)
>>> "abc"[0]
'a'
>>> "abc" + b"def"
Traceback (most recent call last):
...
TypeError: can only concatenate str (not "bytes") to str
An element of bytes is an int from 0 to 255; an element of str is a string of length 1. Python has no separate character type.
The mistake: the wrong encoding. Decoding with an encoding other than the one used to encode either fails or, worse, succeeds with the wrong text. The second outcome produces the familiar garbage called mojibake:
>>> "café".encode("utf-8").decode("latin-1")
'café'
>>> "€".encode("latin-1")
Traceback (most recent call last):
...
UnicodeEncodeError: 'latin-1' codec can't encode character '\u20ac' in position 0: ordinal not in range(256)
Latin-1 maps every byte to one character, so any bytes “decode”, and the two UTF-8 bytes of é become à and ©. Latin-1 also has only 256 characters, so € cannot be encoded in it at all. When you see é or о in output, a UTF-8 text was decoded as Latin-1 or a Windows code page. The rule that prevents both: decode bytes as early as possible, work with str inside the program, encode as late as possible, and name the encoding every time. open(path, encoding="utf-8") does that for files. Without the argument, Python 3.14 uses the locale’s encoding, which is UTF-8 on most macOS and Linux systems and often not on Windows; Python 3.15, released in October 2026, makes UTF-8 the default everywhere (PEP 686). The files note returns to this.
One visible letter, two strings. Unicode can write é as one code point, U+00E9, or as e followed by the combining accent U+0301. The two look the same and are different strings:
>>> a = "\N{LATIN SMALL LETTER E WITH ACUTE}"
>>> b = "e\N{COMBINING ACUTE ACCENT}"
>>> a, b, a == b, len(a), len(b)
('é', 'é', False, 1, 2)
>>> import unicodedata
>>> unicodedata.normalize("NFC", b) == a
True
\N{...} inside a string literal inserts a character by its Unicode name. unicodedata.normalize("NFC", text) composes such pairs into single code points, so that equal-looking text compares equal; the NLP course’s note on text lists the four normalization forms and when each is used. Even len after normalization is not “what a reader counts as a character”: the emoji of a family of three is five code points, three people joined by two invisible joiners, and 18 bytes in UTF-8.
How CPython stores a string. A str in memory is not UTF-8. Since Python 3.3 (PEP 393), CPython stores each string in a fixed width chosen by its widest character: 1 byte per code point if all are below 256, 2 bytes if all are below 65,536, else 4. Every index then costs the same, s[i] is a single array access, which UTF-8 could not offer. sys.getsizeof of ten-character strings shows the three widths (64-bit CPython 3.14):
>>> import sys
>>> [sys.getsizeof(x * 10) for x in ("a", "é", "€", "😀")]
[51, 67, 78, 100]
The ASCII string takes a 40-byte header plus 10 bytes and a terminating zero byte. The others have a larger header, 56 bytes, plus 10 code points and a terminating zero, each of 1, 2 or 4 bytes: , and . One emoji in a long text quadruples the memory of the whole string.
Indexing and slicing#
The rule. s[i] is the code point at position i, counting from 0; a negative index counts from the end, s[-1] being the last. s[start:stop] is the slice from start up to but not including stop; either may be omitted, meaning the start or the end. s[start:stop:step] takes every step-th code point, backwards if step is negative. An index out of range is an error; a slice out of range is not, it is just shorter.
>>> word = "Python"
>>> word[0], word[5], word[-1], word[-6]
('P', 'n', 'n', 'P')
>>> word[0:2], word[2:], word[:2] + word[2:]
('Py', 'thon', 'Python')
>>> word[::2], word[::-1], word[1:100], word[10:]
('Pto', 'nohtyP', 'ython', '')
>>> word[6]
Traceback (most recent call last):
...
IndexError: string index out of range
Why half-open. Indices name the gaps between code points rather than the code points themselves: gap 0 before P, gap 6 after n. word[a:b] is everything between gap a and gap b. Three useful facts follow. The length of word[a:b] is b - a. word[:k] + word[k:] is word for every k, with no overlap and nothing lost. And word[:k] is the first k code points. The same rule holds for lists, tuples and NumPy arrays, and range(a, b) uses it too.
Strings are immutable#
No operation changes a string. Assignment to an index is an error, and every method that seems to change a string returns a new one:
>>> word = "Python"
>>> word[0] = "J"
Traceback (most recent call last):
...
TypeError: 'str' object does not support item assignment
>>> "J" + word[1:]
'Jython'
>>> word.replace("P", "J"), word
('Jython', 'Python')
Immutability makes strings safe to share: as in Values, types and names, a string bound to several names, or used as a dictionary key, can never change under any of them. The price is that building a long string by repeated += creates a new string each time and copies everything so far, a cost that grows with the square of the final length in the worst case (Python documentation, common sequence operations, note 6). Collect the pieces in a list and join them once:
>>> parts = []
>>> for word in ["to", "be", "or", "not"]:
... parts.append(word.upper())
...
>>> " ".join(parts)
'TO BE OR NOT'
Common methods#
A few methods cover most text handling. Each returns a new object; none changes the string.
| Method | What it returns | Example and result |
|---|---|---|
strip() | the string without whitespace at both ends | " a b ".strip() → 'a b' |
split() | a list of the pieces between runs of whitespace | "a b c".split() → ['a', 'b', 'c'] |
split(sep) | a list of the pieces between each occurrence of sep | "a,b,,c".split(",") → ['a', 'b', '', 'c'] |
sep.join(items) | the items joined with sep between them | "-".join(["2026", "10", "22"]) → '2026-10-22' |
lower(), upper() | the string in lower or upper case | "straße".upper() → 'STRASSE' |
casefold() | an aggressive lower case for comparisons | "Straße".casefold() → 'strasse' |
replace(old, new) | every old replaced by new | "Python".replace("P", "J") → 'Jython' |
startswith(p), endswith(p) | whether the string begins or ends with p | "banana".startswith("ban") → True |
find(sub), index(sub) | the first position of sub; find gives −1 if absent, index raises ValueError | "banana".find("n") → 2 |
count(sub) | the number of non-overlapping occurrences | "banana".count("an") → 2 |
isdigit(), isalpha(), isspace() | whether every character is of that kind | "4.2".isdigit() → False |
sub in s tests for a substring: "nan" in "banana" is True. Note the two splits: without an argument, runs of whitespace count as one separator and empty pieces are dropped; with an argument, every occurrence separates, so two commas give an empty piece. "Straße".lower() keeps the ß, so it does not compare equal to "STRASSE".lower(); casefold is designed for case-insensitive comparison and turns ß into ss.
repr against str. The REPL shows a string with repr, which adds quotes and writes special characters as escapes; print writes the characters themselves:
>>> s = "tab\there"
>>> print(s)
tab here
>>> s
'tab\there'
repr is the form for debugging, since it shows invisible characters such as tabs and trailing spaces. A raw string, r"C:\new", treats backslashes as ordinary characters, which is what regular expressions and Windows paths need.
f-strings and format specifications#
An f-string, a literal prefixed with f, evaluates the expressions in braces when the line runs and inserts their values (PEP 498). After the expression, an optional !r applies repr, and an optional colon introduces a format specification, a small language that says how the value is shown (Python documentation, format specification mini-language):
>>> name, pi, n = "Ada", 3.14159265, 1234567
>>> f"Hello, {name}!"
'Hello, Ada!'
>>> f"{pi:.2f}", f"{pi:10.3f}|", f"{pi:<10.3f}|", f"{n:,}", f"{n:_}"
('3.14', ' 3.142|', '3.142 |', '1,234,567', '1_234_567')
>>> f"{0.256:.1%}", f"{255:x}", f"{255:#010b}", f"{42:05d}", f"{1e-7:.2e}"
('25.6%', 'ff', '0b11111111', '00042', '1.00e-07')
>>> f"{name!r}", f"{name:>6}|", f"{name:^7}|", f"{name:*<6}"
("'Ada'", ' Ada|', ' Ada |', 'Ada***')
>>> f"{n=}", f"{pi * 2 = :.3f}"
('n=1234567', 'pi * 2 = 6.283')
Reading the specifications: .2f is fixed-point with 2 decimals; 10.3f pads to width 10, and < aligns left (numbers align right by default, strings left); , and _ group thousands; .1% multiplies by 100 and adds a percent sign; x is hexadecimal, #010b binary with the 0b prefix padded with zeros to width 10; 05d pads an integer with zeros; .2e is scientific notation. ^ centres, and a character before <, > or ^ is the fill. {n=} (since 3.8) prints the expression, an equals sign and the value, which makes quick debugging output. Since 3.12 (PEP 701), the expression may contain the same quotes as the f-string, as in f"{items["a"]}". A specification can itself contain a value in braces, f"{pi:{width}.2f}".
The machine-learning courses print every metric this way: f"{loss:.4f}" for a loss, f"{acc:.1%}" for an accuracy, aligned columns for a table of results, as in the Code section below.
Template strings: values kept apart#
An f-string produces a finished str at once. That is its strength and, in one situation, its danger: once a value has been pasted into text, nothing can tell which parts were written by the programmer and which came from outside. Pasting a user’s comment into HTML, or a name into an SQL query, lets the user’s text act as markup or as code. This is injection, among the most common security bugs.
The rule. Python 3.14 adds template strings, literals prefixed with t (PEP 750). A t-string is written like an f-string, but evaluates to a string.templatelib.Template object, not to a str. The object keeps the literal parts and the interpolated values apart. Its strings are the literal pieces, its interpolations are Interpolation objects, each with the value, the source text of the expression, the conversion ('r', 's', 'a' or None) and the format specification; iterating over a template yields the pieces in order. A template has no text of its own: some function, a renderer, must turn it into text, and that function can treat the values differently from the literal parts.
>>> name = "Ada"
>>> template = t"Hello, {name}!"
>>> type(template)
<class 'string.templatelib.Template'>
>>> template.strings, template.values
(('Hello, ', '!'), ('Ada',))
>>> list(template)
['Hello, ', Interpolation('Ada', 'name', None, ''), '!']
Worked example: safe HTML. A renderer that escapes every value but leaves the literal markup alone:
>>> from string.templatelib import Interpolation, convert
>>> import html
>>> def render_html(template):
... parts = []
... for item in template:
... if isinstance(item, Interpolation):
... value = convert(item.value, item.conversion)
... parts.append(html.escape(format(value, item.format_spec)))
... else:
... parts.append(item)
... return "".join(parts)
...
>>> comment = "<script>alert('hi')</script>"
>>> price = 3.5
>>> f"<p>{comment}</p>"
"<p><script>alert('hi')</script></p>"
>>> render_html(t"<p>{comment}</p> costs <b>{price:.2f}</b>")
'<p><script>alert('hi')</script></p> costs <b>3.50</b>'
The f-string pasted the script into the page. The template let the renderer see that comment was a value, and html.escape turned its < and ' into entities, so a browser shows the text instead of running it; the literal <p> and <b> stayed markup. The renderer must apply the conversion and the format specification itself, with convert and format; a renderer that forgets them would print 3.5 instead of 3.50.
Worked example: an SQL query with parameters. A renderer can also refuse to paste values at all, and pass them separately, the way database drivers want them:
>>> def to_sql(template):
... query, params = [], []
... for item in template:
... if isinstance(item, Interpolation):
... query.append("?")
... params.append(item.value)
... else:
... query.append(item)
... return "".join(query), params
...
>>> user = "x'; DROP TABLE users; --"
>>> to_sql(t"SELECT * FROM users WHERE name = {user}")
('SELECT * FROM users WHERE name = ?', ["x'; DROP TABLE users; --"])
>>> f"SELECT * FROM users WHERE name = '{user}'"
"SELECT * FROM users WHERE name = 'x'; DROP TABLE users; --'"
The f-string version is a query that deletes a table; the template version is a query with a placeholder and a parameter, which the database treats as data whatever it contains.
What a template is not. It is not a string: str(template) gives its repr, not text, and t"a{1}" + "b" raises TypeError; only a renderer makes text. Templates are worth it where values must be treated specially (HTML, SQL, shell commands, structured logging); for ordinary output, f-strings remain the tool. The standard library in 3.14 provides the types and convert, and renderers come from the libraries that need them.
Text processing for NLP#
Every NLP pipeline starts with the operations of this note: normalize the Unicode, change the case, cut the text into units. A minimal version:
>>> import re
>>> text = "Don't panic: the café opens at 9:30!"
>>> text.lower().split()
["don't", 'panic:', 'the', 'café', 'opens', 'at', '9:30!']
>>> re.findall(r"\w+|[^\w\s]", text)
['Don', "'", 't', 'panic', ':', 'the', 'café', 'opens', 'at', '9', ':', '30', '!']
split leaves punctuation attached to words. The regular expression \w+|[^\w\s], from the module re, takes either a run of word characters (letters, digits and the underscore, in any script, since Python’s \w is Unicode-aware) or a single character that is neither a word character nor whitespace; it separates punctuation and splits Don't into three tokens. Each choice here (lower-casing, normalizing, what counts as a word) changes the vocabulary a model sees, and the NLP course discusses them as modelling decisions in Text as data. Modern models replace word splitting by subword tokenizers, and byte-level ones such as GPT-2’s start from exactly the UTF-8 bytes of this note: their base vocabulary is the 256 byte values, so no text is ever out of vocabulary (Tokenization). The lengths a model counts are tokens, not code points and not bytes, and the three disagree:
>>> words = ["cat", "кот", "猫", "🐈"]
>>> [(w, len(w), len(w.encode("utf-8"))) for w in words]
[('cat', 3, 3), ('кот', 3, 6), ('猫', 1, 3), ('🐈', 1, 4)]
What changed#
| Text as bytes (the baseline) | Python’s str | |
|---|---|---|
| Unit | a byte | a Unicode code point |
len, indices, slices | count bytes; can cut a character in half | count code points |
| Bytes | the only representation | only at the boundary: encode and decode, with a named encoding |
| Changing text | in place | immutable; methods return new strings; build with join |
| Putting values into text | concatenation | f-strings with format specifications; t-strings when values need a renderer |
Limitations#
- Code points are not what readers see. Combining marks, emoji sequences and some scripts make one visible character of several code points; counting those (grapheme clusters) needs a third-party library, and normalization only partly helps.
- Regular expressions are only used. The
remodule has its own language, documented in the Regular Expression HOWTO; this course uses short patterns and explains each where it appears. - Locale-dependent defaults. On 3.14 and earlier, where UTF-8 is not yet the default, code that opens files without
encoding=behaves differently on Windows; always pass it. - Template strings are new. The renderers above illustrate the mechanism. Production code should use a maintained library for HTML escaping and the parameter API of its database driver.
What you should remember#
- A
stris an immutable sequence of Unicode code points;len, indexing and slicing count code points. bytesare what files and networks carry.encodeanddecodeconvert at the boundary, always with a named encoding, almost always UTF-8, in which a code point takes 1 to 4 bytes.- Mojibake such as
émeans UTF-8 bytes decoded with the wrong encoding. Normalize with NFC before comparing text that may contain combining marks. - Slices are half-open:
s[a:b]hasb - acode points ands[:k] + s[k:] == s. Negative indices count from the end. - Strings never change; build long text with
"".join(parts). - f-strings format values with specifications such as
.3f,,,.1%,>10;{x=}prints the expression too. - A t-string (3.14) is a
Templatethat keeps literal text and values apart, so that a renderer can escape or parameterize the values.
Code#
The script runs each part of the note: code points against UTF-8 bytes for words in four scripts and an emoji, normalization of a decomposed letter, the wrong-encoding mistake, slicing, a small normalizer and tokenizer of the kind NLP pipelines start with, a table formatted with format specifications, and a template string rendered safely into HTML. Run it with python -I text.py; it uses only the standard library. The alignment of the first block is off for 猫 and 🐈 because the format pads by code points while a terminal draws those characters two columns wide, one more way in which “length” depends on who is counting.
"""Strings as code points, bytes, slices, formats and templates (Python 3.14)."""
import html
import re
import unicodedata
from string.templatelib import Interpolation, Template, convert
# 1. Code points against UTF-8 bytes
for word in ["cat", "naïve", "кот", "€", "猫", "🐈"]:
data = word.encode("utf-8")
print(f"{word!r:8} len={len(word)} bytes={len(data)} {data.hex(' ')}")
# 2. One visible letter, two spellings; NFC makes them equal
composed, decomposed = "caf\N{LATIN SMALL LETTER E WITH ACUTE}", "cafe\N{COMBINING ACUTE ACCENT}"
print(composed == decomposed, len(composed), len(decomposed),
unicodedata.normalize("NFC", decomposed) == composed)
# 3. Decoding with the wrong codec: no error, wrong text
print("café".encode("utf-8").decode("latin-1"))
try:
"café".encode("utf-8")[:4].decode("utf-8") # cut inside the two bytes of é
except UnicodeDecodeError as err:
print("UnicodeDecodeError:", err.reason)
# 4. Indexing and slicing: half-open ranges, negative indices
s = "Python"
print(s[0], s[-1], s[1:4], s[:2] + s[2:], s[::-1], repr(s[10:]))
# 5. A tiny normalizer and tokenizer of the kind NLP pipelines start with
def tokenize(text):
text = unicodedata.normalize("NFC", text).casefold()
return re.findall(r"\w+|[^\w\s]", text)
print(tokenize("Don't PANIC: the cafe\N{COMBINING ACUTE ACCENT} opens at 9:30!"))
# 6. f-strings with format specifications
rows = [("loss", 0.034567, 1200), ("accuracy", 0.98213, 1200), ("tokens", 1234567, 3)]
for name, value, n in rows:
shown = f"{value:,}" if isinstance(value, int) else f"{value:.3f}"
print(f"{name:<10}|{shown:>10}|{n:>6}|{n / 1200:6.1%}")
# 7. Template strings: the values stay separate until a renderer decides
def render_html(template: Template) -> str:
out = []
for item in template:
if isinstance(item, Interpolation):
value = convert(item.value, item.conversion)
out.append(html.escape(format(value, item.format_spec)))
else:
out.append(item)
return "".join(out)
comment, price = "<b>great</b> & cheap", 3.5
page = t"<p>{comment}</p><p>{price:.2f} EUR</p>"
print(page.strings)
print(page.values)
print(render_html(page))
# Output with CPython 3.14.7 (the same on any platform):
# 'cat' len=3 bytes=3 63 61 74
# 'naïve' len=5 bytes=6 6e 61 c3 af 76 65
# 'кот' len=3 bytes=6 d0 ba d0 be d1 82
# '€' len=1 bytes=3 e2 82 ac
# '猫' len=1 bytes=3 e7 8c ab
# '🐈' len=1 bytes=4 f0 9f 90 88
# False 4 5 True
# café
# UnicodeDecodeError: unexpected end of data
# P n yth Python nohtyP ''
# ['don', "'", 't', 'panic', ':', 'the', 'café', 'opens', 'at', '9', ':', '30', '!']
# loss | 0.035| 1200|100.0%
# accuracy | 0.982| 1200|100.0%
# tokens | 1,234,567| 3| 0.2%
# ('<p>', '</p><p>', ' EUR</p>')
# ('<b>great</b> & cheap', 3.5)
# <p><b>great</b> & cheap</p><p>3.50 EUR</p>
The tokenizer receives cafe with a separate combining accent, and NFC turns it into the single code point é before the regular expression runs; without normalization, \w+ would still keep the accent with its letter, but the token would not be equal to the café typed with one code point.
Next#
This note ends the Getting Started section: a program can now hold values, make choices, repeat, be split into functions, and handle text. The next section is about holding many values at once. The next note opens the list, the most used container in Python, and shows what it is in memory, an array of references that grows, and therefore what each of its operations costs.
References#
- Python documentation (3.14): Text sequence type —
strand common sequence operations (note 6 on repeated concatenation); Format specification mini-language;string.templatelib; Unicode HOWTO;codecs;unicodedata;re; What’s New in Python 3.14 (template strings). - J. Baker, G. van Rossum, P. Everitt, K. Aono, L. Nikolaou, D. Peck. PEP 750 — Template Strings. 2024.
- E. V. Smith. PEP 498 — Literal String Interpolation. 2015. P. Galindo Salgado, B. Taskaya, L. Nikolaou, M. Gómez Macías. PEP 701 — Syntactic formalization of f-strings. 2022.
- M. v. Löwis. PEP 393 — Flexible String Representation. 2010.
- N. Inada. PEP 686 — Make UTF-8 mode default. 2022.
- The Unicode Consortium. The Unicode Standard, ch. 2 (general structure: code points, encoding forms) and Unicode Standard Annex #15: Unicode Normalization Forms.
- L. Ramalho. Fluent Python, 2nd ed. O’Reilly, 2022. Ch. 4 (Unicode text versus bytes).