cwcwidth
cwcwidth provides efficient Python bindings for the POSIX wcwidth and wcswidth functions, which calculate the printable length of Unicode characters and strings on a terminal. It is actively maintained with version 0.1.12 being the latest, featuring regular updates that often include support for new Python versions, dropping support for older ones, and updating to the latest Unicode definitions.
Warnings
- breaking cwcwidth frequently drops support for older Python versions with new releases. For example, version 0.1.12 dropped Python 3.10 support, 0.1.11 dropped 3.9, and 0.1.10 dropped 3.8. Ensure your Python environment meets the `requires_python` specification for the installed library version.
- gotcha The `wcwidth` and `wcswidth` functions return -1 if they encounter non-printable C0 or C1 control characters within the input string. This behavior is consistent with the underlying POSIX C functions.
- gotcha The library updates its internal Unicode definition periodically (e.g., version 0.1.10 updated to Unicode 15.1). This might lead to subtle changes in width calculations for certain characters if your application relies on a specific Unicode version or if the terminal's Unicode interpretation differs.
Install
-
pip install cwcwidth
Imports
- wcwidth
from cwcwidth import wcwidth
- wcswidth
from cwcwidth import wcswidth
Quickstart
from cwcwidth import wcwidth, wcswidth
# Calculate width of a single character
char_width_a = wcwidth('a')
char_width_kanji = wcwidth('語')
# Calculate width of a string
string_width_hello = wcswidth('Hello')
string_width_japanese = wcswidth('コンニチハ, セカイ!')
# Calculate width of a substring (first 5 characters)
string_width_partial = wcswidth('コンニチハ, セカイ!', 5)
print(f"Width of 'a': {char_width_a}")
print(f"Width of '語': {char_width_kanji}")
print(f"Width of 'Hello': {string_width_hello}")
print(f"Width of 'コンニチハ, セカイ!': {string_width_japanese}")
print(f"Width of first 5 chars of 'コンニチハ, セカイ!': {string_width_partial}")
# Example with a non-printable character (returns -1)
non_printable_width = wcwidth('\x01') # Start of Heading control character
print(f"Width of non-printable char '\x01': {non_printable_width}")