cwcwidth

0.1.12 · active · verified Tue Apr 14

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

Install

Imports

Quickstart

This quickstart demonstrates how to use `wcwidth` for single Unicode characters and `wcswidth` for entire strings or substrings, calculating their display width on a terminal. It also shows the behavior with non-printable control characters.

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}")

view raw JSON →