pysnippets.strings.byte_size
Size of a string in bytes
byte_size(text: str, encoding: str = "utf-8") -> int
Count the bytes a string takes up once encoded, which len() doesn't tell you.
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))- 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")6Edit 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).
python 3.14 · in your browser
Loading Python 3.14 in your browser (≈7 MB, cached after the first time)…
Tab inserts four spaces. Press Escape, then Tab, to leave the editor. Control or Command plus Enter runs the examples.
How it works
len(text)counts code points..encode()produces the bytes that are actually stored or sent; theirlenis 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
- 3.11✓passes
- 3.12✓passes
- 3.13✓passes
- 3.14✓passes
Import
from 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.