fluttersmith/py-snippetsGitHub ↗

Size of a string in bytes

Count the bytes a string takes up once encoded, which len() doesn't tell you.

Strings#textO(n) time✓ 3 examples pass on 3.11–3.14

A database column holds 255 bytes, an emoji is 4 of them, and len('😀') is 1.

byte_size.py✓ ruff · mypy --strict
def byte_size(text: str, encoding: str = "utf-8") -> int:
    """Return the number of bytes ``text`` takes up in ``encoding``."""
    return len(text.encode(encoding))
  1. len(text) counts code points; this counts bytes
examples✓ 3 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> byte_size("Hello World")11passed on Python 3.11 to 3.14: >>> byte_size("😀")4passed on Python 3.11 to 3.14: >>> byte_size("😀", "utf-16")6
Edit the function or the examples and run the doctests here, on Python 3.14. Python loads only when you click (about 7 MB, cached after the first time).

How it works

  • len(text) counts code points.
  • .encode() produces the bytes that are actually stored or sent; their len is the size.
  • The encoding matters: the same emoji is 4 bytes in UTF-8 and 6 in UTF-16, including the 2-byte BOM.

Complexity: O(n) time, O(n) space

Importfrom pysnippets.strings.byte_size import byte_sizeNo dependencies: copy byte_size.py into your project, or clone the repo.

Adapted from byte-size in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: Added the encoding parameter; typed. Suggest an edit.