Skip to content
BIASED

Strings and text

A string as an immutable sequence of code points, UTF-8 and bytes, encoding mistakes and normalization, slicing, text-cleaning methods, f-strings with format specifications, the template strings of Python 3.14 and a first tokenizer for NLP.

A string is a sequence of code points

The topic Functions finished the skeleton of a program: values and names, branches and loops, and functions that give repeated code a name. Almost every program also reads and writes text: file names, log lines, tables of metrics, and in natural language processing the data itself. Text looks simple and is not. A letter can take one byte in a file or four, and two strings that look the same can compare unequal.

A Python string, str, is a sequence of code points. A code point is the number that Unicode assigns to a character. It is written as U+ and at least four hexadecimal digits: U+0041 is A, U+20AC is €. The function ord gives the code point of a one-character string, and chr goes back:

s = "naïve €"
print(len(s))
print(ord("n"), ord("ï"), ord("€"))
print(chr(239), chr(8364), s[2])
print(type(s[2]), len(s[2]))
7
110 239 8364
ï € ï
<class 'str'> 1

The string holds seven code points: five letters, a space and the euro sign. len counts code points, and indices count them too: s[2] is the third one, ï. The number 8364 is 20AC in hexadecimal, so chr(8364) is U+20AC. Python has no separate character type: an element of a string is again a string, of length 1.

Every character has its code point: Latin and Cyrillic letters, Chinese characters, mathematical symbols. Even the cat emoji 🐈 is a single code point, U+1F408.

Bytes and UTF-8

Files, networks and memory hold bytes, numbers from 0 to 255. Unicode has far more than 256 characters, so most code points need several bytes. The rule that turns code points into bytes is an encoding, and today it is almost always UTF-8. The method encode turns a str into bytes, and decode turns bytes back into a str:

s = "naïve €"
data = s.encode("utf-8")
print(data)
print(len(s), len(data), type(data))
print(data.decode("utf-8") == s)
print(data[0], s[0])
b'na\xc3\xafve \xe2\x82\xac'
7 10 <class 'bytes'>
True
110 n

A bytes value is displayed with printable ASCII bytes as characters and every other byte as \x and two hexadecimal digits. The ï became the two bytes C3 AF, and € the three bytes E2 82 AC. So 7 code points take 10 bytes. UTF-8 stores each code point in one to four bytes:

  • 1 byte for the 128 ASCII characters (Latin letters, digits, punctuation), the same byte as in plain ASCII;
  • 2 bytes for most accented Latin letters and for Cyrillic;
  • 3 bytes for most other characters in common use, such as € and Chinese characters;
  • 4 bytes for emoji.

str and bytes are different types. An element of bytes is an int, an element of str is a string. Python refuses to guess an encoding between them: "abc" + b"def" stops with TypeError: can only concatenate str (not "bytes") to str.

Inside the program, a str is not stored as UTF-8. CPython gives each string a fixed width per code point, chosen by its widest character: 1 byte if all code points are below 256, 2 bytes if all are below 65,536, otherwise 4. Then s[i] is a single array access for any i, which variable-width UTF-8 could not offer. On 64-bit CPython 3.14, strings of 1000 characters show the widths:

import sys
for ch in ["a", "é", "€", "🐈"]:
    print(ch, sys.getsizeof(ch * 1000))
a 1041
é 1057
€ 2058
🐈 4060

Beyond a header of 40 to 56 bytes, that is 1, 1, 2 and 4 bytes per code point (é is U+00E9, below 256). One emoji in a long text quadruples the memory of the whole string.

Encoding mistakes and normalization

Two mistakes with encodings are worth recognizing on sight. The first is cutting bytes in the middle of a character. In UTF-8 the first byte of a character says how many bytes follow, so a cut character is invalid. Here [:2] keeps the first two bytes; slices come later in this topic:

print("€".encode("utf-8")[:2].decode("utf-8"))
UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 0-1: unexpected end of data

The second mistake is worse: decoding with an encoding other than the one used to encode. It can succeed and give the wrong text. Latin-1 maps every byte to one character, its first 128 characters are ASCII, so any bytes "decode":

print("café".encode("utf-8").decode("latin-1"))
café

The two UTF-8 bytes of é became two characters, à and ©. Such garbage is called mojibake. When output shows é or о, UTF-8 bytes were decoded as Latin-1 or as a Windows code page.

The rule that prevents both mistakes: decode bytes as early as possible, work with str inside the program, encode as late as possible, and name the encoding every time. For files that means open(path, encoding="utf-8"); the topic Files and exceptions returns to it. Without the argument Python 3.14 uses the system locale's encoding. That is UTF-8 on most macOS and Linux machines and often something else on Windows. Python 3.15 makes UTF-8 the default everywhere (PEP 686).

One more surprise: one visible letter can be two different strings. Unicode writes é either as one code point U+00E9 or as e followed by a combining accent U+0301. Inside a literal, \N{...} inserts a character by its Unicode name:

import unicodedata
 
a = "caf\N{LATIN SMALL LETTER E WITH ACUTE}"
b = "cafe\N{COMBINING ACUTE ACCENT}"
print(a, b, a == b, len(a), len(b))
print(unicodedata.normalize("NFC", b) == a)
café café False 4 5
True

unicodedata.normalize("NFC", text) composes such pairs into single code points, so that equal-looking text compares equal. Normalize text that comes from different sources before you compare or count it.

Indices, slices and immutability

s[i] is the code point at position i, counting from 0. A negative index counts from the end: s[-1] is the last one. s[start:stop] is a slice, from start up to but not including stop; an omitted bound means the start or the end. s[start:stop:step] takes every step-th code point, backwards if step is negative:

word = "Python"
print(word[0], word[-1], word[1:4], word[:2], word[2:])
print(word[::2], word[::-1], word[1:100], repr(word[10:]))
print(word[:3] + word[3:] == word)
P n yth Py thon
Pto nohtyP ython ''
True

Think of indices as the gaps between code points: gap 0 before P, gap 6 after n. A slice word[a:b] is everything between gap a and gap b. So it has b - a code points, and word[:k] + word[k:] is the whole word for every k. A slice past the end is not an error, it is just shorter; word[10:] is the empty string. A single index past the end, word[6], raises IndexError. Lists, tuples, NumPy arrays and range(a, b) follow the same half-open rule.

Strings are immutable: no operation changes a string. A method that seems to change one returns a new string, and assignment to an index is an error:

word = "Python"
print(word.replace("P", "J"), word)
word[0] = "J"
Jython Python
TypeError: 'str' object does not support item assignment

The first print runs, then the third line stops the program. Immutability makes strings safe to share between names, as in the topic Values, types and names. The price: text += piece in a loop builds a new string each time and copies everything collected so far. For long texts the total work can grow like the square of the length. Collect the pieces in a list and join them once:

losses = [0.91, 0.64, 0.47, 0.41]
parts = []
for loss in losses:
    parts.append(str(loss))
print(" -> ".join(parts))
0.91 -> 0.64 -> 0.47 -> 0.41

Methods: clean and cut

A handful of methods covers most text cleaning. Each one returns a new object and leaves the string unchanged. Here they parse a line of a metrics file and answer a few questions about text:

line = "  3,0.4127,,0.88\n"
fields = line.strip().split(",")
print(fields)
print("-".join(["2026", "10", "30"]))
print("a b   c".split())
print("Straße".lower(), "Straße".casefold())
print("banana".find("n"), "banana".find("x"), "banana".count("an"), "nan" in "banana")
print("val_loss".startswith("val"), "model.pt".endswith(".pt"))
['3', '0.4127', '', '0.88']
2026-10-30
['a', 'b', 'c']
straße strasse
2 -1 2 True
True True
  • strip() removes whitespace at both ends, including the newline \n.
  • split(sep) cuts at every occurrence of sep, so two commas in a row give an empty field ''.
  • split() with no argument is different. It treats each run of whitespace as one separator and drops empty pieces.
  • sep.join(items) is the inverse: it glues strings with sep between them.
  • casefold() is the lower case meant for comparisons. lower() keeps ß, casefold() turns it into ss, so "Straße" and "STRASSE" become equal.
  • find gives the first position of a substring, or −1 if it is absent. count counts non-overlapping occurrences, and in tests whether a substring occurs at all.

When you debug, print strings with repr. print(s) writes the characters themselves, while repr(s) adds quotes and shows invisible characters as escapes. A tab and a trailing space are invisible in print("tab\there "), but repr shows 'tab\there '. The REPL displays values with repr for this reason. A raw string such as r"C:\new" treats backslashes as ordinary characters, which regular expressions and Windows paths need: without the r, \n is a newline.

f-strings and format specifications

An f-string, a literal with the prefix f, evaluates the expressions in braces when the line runs and inserts their values. After the expression, a colon starts a format specification, a small language that says how to show the value. It is how the machine learning courses print every metric:

loss, acc, n = 0.034567, 0.98213, 1234567
print(f"{loss:.4f}", f"{acc:.1%}", f"{n:,}", f"{n:_}")
print(f"{loss:.2e}", f"{7:03d}", f"{255:x}", f"{255:08b}")
print(f"[{'loss':<8}]", f"[{'loss':>8}]", f"[{'loss':^8}]", f"[{acc:8.3f}]")
print(f"{loss=}", f"{acc * 100 = :.1f}")
0.0346 98.2% 1,234,567 1_234_567
3.46e-02 007 ff 11111111
[loss    ] [    loss] [  loss  ] [   0.982]
loss=0.034567 acc * 100 = 98.2

Reading the specifications:

  • .4f is fixed-point with 4 decimals; .2e is scientific notation with 2.
  • .1% multiplies by 100, keeps 1 decimal and adds a percent sign.
  • , and _ group thousands.
  • 03d pads an integer with zeros to width 3; x is hexadecimal, 08b binary padded to width 8.
  • <, > and ^ align left, right and centre within the width that follows. Numbers align right by default, strings left. The width is a minimum: a longer value is never cut.
  • {loss=} prints the expression, an equals sign and the value, handy for a quick debug line.

Width and precision together give aligned tables. A training log over the per-epoch losses:

losses = [0.9134, 0.6421, 0.4718, 0.4105]
print(f"{'epoch':>5} | {'loss':>6}")
for epoch, loss in enumerate(losses, start=1):
    print(f"{epoch:>5} | {loss:>6.3f}")
epoch |   loss
    1 |  0.913
    2 |  0.642
    3 |  0.472
    4 |  0.410

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 is pasted into text, nothing can tell which parts the programmer wrote and which came from outside. Paste a user's comment into HTML, or a name into an SQL query, and the user's text can act as markup or as code. This is injection, one of the most common security bugs.

Python 3.14 adds template strings, literals with the prefix t (PEP 750). A t-string is written like an f-string, but its value is a Template object, not a str. The object keeps the literal pieces and the interpolated values apart:

name = "Ada"
template = t"Hello, {name}!"
print(type(template))
print(template.strings, template.values)
print(list(template))
<class 'string.templatelib.Template'>
('Hello, ', '!') ('Ada',)
['Hello, ', Interpolation('Ada', 'name', None, ''), '!']

Iterating over a template yields the pieces in order. Each value arrives as an Interpolation with four fields: the value, the source text of the expression, the conversion ('r' for !r, or None) and the format specification. A template has no text of its own. A function called a renderer turns it into text, and it can treat values differently from literal pieces. This renderer escapes every value and leaves the markup alone:

import html
from string.templatelib import Interpolation, convert
 
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, price = "<script>alert('hi')</script>", 3.5
print(f"<p>{comment}</p>")
print(render_html(t"<p>{comment}</p> costs <b>{price:.2f}</b>"))
<p><script>alert('hi')</script></p>
<p>&lt;script&gt;alert(&#x27;hi&#x27;)&lt;/script&gt;</p> costs <b>3.50</b>

The f-string pasted the script into the page. The renderer saw that comment was a value, and html.escape turned its < and ' into entities, so a browser shows the text instead of running it. The renderer applies the conversion and the format specification itself, with convert and format. Forget them, and the price prints as 3.5, not 3.50. A renderer for SQL can go further and never paste values at all: it puts ? in the query and passes the values to the database separately.

A template is not a string. str(template) gives its repr, not text, and t"a{1}" + "b" raises TypeError. Use t-strings where values need special treatment: HTML, SQL, shell commands. For ordinary output, f-strings remain the tool.

First steps of text processing

Every natural language processing pipeline starts with the operations of this topic: normalize the Unicode, fold the case, cut the text into units called tokens. A minimal tokenizer:

import re
import unicodedata
 
def tokenize(text):
    text = unicodedata.normalize("NFC", text).casefold()
    return re.findall(r"\w+|[^\w\s]", text)
 
text = "Don't PANIC: the cafe\N{COMBINING ACUTE ACCENT} opens at 9:30!"
print(text.split())
print(tokenize(text))
["Don't", 'PANIC:', 'the', 'café', 'opens', 'at', '9:30!']
['don', "'", 't', 'panic', ':', 'the', 'café', 'opens', 'at', '9', ':', '30', '!']

split leaves punctuation stuck to the words. The regular expression \w+|[^\w\s], from the module re, matches either a run of word characters or one character that is neither a word character nor whitespace. Word characters are letters, digits and the underscore, in any script: Python's \w knows Unicode. The raw string keeps the backslashes for re. So the pattern separates punctuation, and Don't becomes three tokens.

Each choice here, lower-casing, normalizing, what counts as a word, changes the vocabulary a model sees. The course Natural Language Processing treats these choices as modelling decisions in the topics Text as data and Tokenization. Modern models split text into subwords, and byte-level tokenizers start from the UTF-8 bytes of this topic: their base vocabulary is the 256 byte values. The three lengths then disagree:

for w in ["cat", "кот", "猫", "🐈"]:
    print(w, len(w), len(w.encode("utf-8")))
cat 3 3
кот 3 6
猫 1 3
🐈 1 4

split and re.findall return their tokens as a list, and lists have already appeared in this topic: the fields of a line, the pieces for join. What a list is in memory, why append is cheap and inserting at the front is not, is the topic Lists and tuples.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.