Character Encoding: ASCII, Unicode, UTF-8 and Garbled Text
Computers store bytes, not letters. A character encoding is the agreement that says which bytes stand for which characters. When the program that writes text and the program that reads it agree, everything works. When they do not, "café" turns into "café", apostrophes become "’", and unknown bytes show up as �. This page explains the three ideas you need (ASCII, Unicode, UTF-8) and the habits that prevent garbled text.
Examples use Python 3.10 or later and Node.js 22 or later; the shell commands were run on macOS and also exist on Linux. All output shown is real.
ASCII: the 128 characters everything shares
ASCII assigns the numbers 0 to 127 to the English letters, digits, punctuation, space and control characters such as newline (10) and tab (9). A is 65, a is 97, 0 is 48. It fits in 7 bits, so every ASCII character is one byte.
ASCII has no é, ü, €, Cyrillic, Chinese or emoji. For decades, each region filled the spare values 128 to 255 differently: ISO-8859-1 (Latin-1) for Western Europe, Windows-1252 (cp1252) on Windows, and many others. The same byte, 0xE9, is é in Latin-1 and something else entirely in a Cyrillic code page. That ambiguity is the root of most garbled text.
Unicode: one number for every character
Unicode gives every character in every script a single number, called a code point, written U+ and hexadecimal: U+0041 is A, U+00E9 is é, U+20AC is €, U+1F600 is the grinning face emoji, U+1D11E is the musical symbol 𝄞. Code points run from U+0000 to U+10FFFF. Unicode on its own says nothing about bytes; an encoding turns code points into bytes.
UTF-8: the encoding to use
UTF-8 (RFC 3629) stores each code point in 1 to 4 bytes. Its key property is that the first 128 code points are stored as the same single bytes as ASCII, so every ASCII file is already valid UTF-8. It is the standard encoding for the web, for JSON exchanged between systems, and for most source code.
for ch in ["A", "é", "€", "𝄞"]:
data = ch.encode("utf-8")
print(f"{ch} U+{ord(ch):04X} {len(data)} byte(s): {data.hex(' ').upper()}")
A U+0041 1 byte(s): 41
é U+00E9 2 byte(s): C3 A9
€ U+20AC 3 byte(s): E2 82 AC
𝄞 U+1D11E 4 byte(s): F0 9D 84 9E
UTF-16 (used inside Windows, Java and JavaScript strings) stores most characters in 2 bytes and the rest, including most emoji, as a pair of 2-byte "surrogates". You mostly meet it through string lengths, below.
Text and bytes in Python
Python 3 keeps them apart: a str is a sequence of code points, bytes is raw data. encode goes from text to bytes, decode from bytes to text, and you always say which encoding:
text = "naïve café"
data = text.encode("utf-8") # str -> bytes
print(len(text), len(data)) # characters vs bytes
print(data)
print(data.decode("utf-8") == text)
# Decoding with the wrong encoding fails loudly...
try:
data.decode("ascii")
except UnicodeDecodeError as err:
print(err)
# ...or, worse, silently produces the wrong characters (mojibake)
print(data.decode("cp1252"))
10 12
b'na\xc3\xafve caf\xc3\xa9'
True
'ascii' codec can't decode byte 0xc3 in position 2: ordinal not in range(128)
naïve café
The last line is mojibake: UTF-8 bytes read as Windows-1252. Each two-byte UTF-8 character became two wrong characters. Typical signs are à or  before another symbol (é shows as é) and †sequences in place of curly quotes and dashes.
Reading and writing files
Always pass encoding="utf-8" to open, read_text and write_text. Without it, Python uses a default that depends on the operating system's locale; on Windows that has often been a legacy code page, so a script that works on one machine garbles text on another.
from pathlib import Path
path = Path("notes.txt")
path.write_text("Grüße, 世界\n", encoding="utf-8") # always name the encoding
print(path.read_bytes())
print(path.read_text(encoding="utf-8"), end="")
# A file you cannot fix: keep going, mark bad bytes with U+FFFD
broken = b"price: 10\xa3\n" # a Latin-1 pound sign in a "UTF-8" file
print(broken.decode("utf-8", errors="replace"), end="")
# Files saved by some Windows editors start with a byte order mark (BOM)
bom_file = b"\xef\xbb\xbfid,name\n"
print(repr(bom_file.decode("utf-8")), repr(bom_file.decode("utf-8-sig")))
b'Gr\xc3\xbc\xc3\x9fe, \xe4\xb8\x96\xe7\x95\x8c\n'
Grüße, 世界
price: 10�
'\ufeffid,name\n' 'id,name\n'
errors="replace"substitutes U+FFFD (�, the replacement character) for bytes that are not valid UTF-8. Use it when you must keep going, and log that data was lost; the default,errors="strict", raisesUnicodeDecodeError, which is usually what you want.- Some Windows tools put a byte order mark (
EF BB BF) at the start of UTF-8 files. It shows up asglued to your first column name. Read such files withencoding="utf-8-sig", which removes it.
Repairing mojibake
If text was decoded with the wrong encoding and nothing was lost, reverse the mistake: encode with the wrong encoding to get the original bytes back, then decode them correctly.
garbled = "It’s a café" # UTF-8 bytes that were decoded as Windows-1252
# Undo the wrong decode (back to the original bytes), then decode correctly
repaired = garbled.encode("cp1252").decode("utf-8")
print(repaired)
It’s a café
This only works when every byte survived. If the bad text was saved again, or bytes were replaced with ? or �, the information is gone and the fix is to go back to the source. Better still, fix the place where the wrong decode happened.
Same text, different code points
"é" can be one code point (U+00E9) or two: e followed by a combining accent (U+0301). They look identical but compare as different, which breaks searches, deduplication and usernames. Normalize text before comparing it:
import unicodedata
a = "café" # é as one code point
b = "café" # e + combining acute accent
print(a, b, a == b, len(a), len(b))
nfc = unicodedata.normalize
print(nfc("NFC", a) == nfc("NFC", b))
café café False 4 5
True
Lengths in JavaScript
A JavaScript string's length counts UTF-16 code units, not characters, so any character above U+FFFF, including 𝄞 and most emoji, counts as 2:
const s = "café 𝄞";
console.log(s.length); // UTF-16 code units
console.log([...s].length); // code points
console.log(new TextEncoder().encode(s).length); // UTF-8 bytes
console.log(new TextDecoder("utf-8").decode(new Uint8Array([0x63, 0xc3, 0xa9])));
7
6
10
cé
Use [...s].length for code points and the UTF-8 byte count when a limit is in bytes (database columns, HTTP headers). Neither is the same as what a reader sees as one character: a flag or a family emoji is several code points.
Finding and converting the encoding of a file
printf 'caf\xc3\xa9\n' > utf8.txt
printf 'caf\xe9\n' > latin1.txt
file utf8.txt latin1.txt
xxd latin1.txt
iconv -f WINDOWS-1252 -t UTF-8 latin1.txt > converted.txt
xxd converted.txt
utf8.txt: Unicode text, UTF-8 text
latin1.txt: ISO-8859 text
00000000: 6361 66e9 0a caf..
00000000: 6361 66c3 a90a caf...
file guesses, and its guess is not proof; the hex dump from xxd is. A lone e9 is Latin-1 or Windows-1252, while c3 a9 is é in UTF-8. iconv converts between them; write to a new file rather than over the original.
Habits that prevent garbled text
- UTF-8 everywhere: files, databases, HTTP responses. In HTML, put
<meta charset="utf-8">first in the<head>and sendContent-Type: text/html; charset=utf-8. In MySQL, the full UTF-8 character set isutf8mb4; its olderutf8cannot store 4-byte characters such as emoji. - Decode at the edges, work in text, encode at the edges. Convert bytes to
strwhen data comes in, and back to bytes when it goes out. - Name the encoding every time you open a file, call
encode/decodeor set up a connection. - Do not confuse encodings with escaping or Base64. UTF-8, URL encoding (
%C3%A9) and Base64 are all reversible representations of the same bytes. The Base64 Converter encodes text as UTF-8 first, so "é" always becomesw6k=; Base64 explained covers the details.
JSON is always UTF-8 between systems, which is one reason it travels well; the JSON Formatter keeps non-ASCII characters intact. Python's Unicode HOWTO goes deeper on everything above.