east_asian_width Aligns CJK Columns

East Asian wide glyphs occupy two terminal cells, so column padding must measure display width with unicodedata.east_asian_width before ljust.

PythonData Integrity

Code

pythonsnippet
20 lines
import unicodedata


def display_width(text: str) -> int:
    """CJK glyphs occupy two terminal cells, ASCII one."""
    return sum(
        2 if unicodedata.east_asian_width(char) in ("F", "W") else 1
        for char in text
    )


def pad(text: str, width: int) -> str:
    return text + " " * (width - display_width(text))


rows = [("user", "数"), ("bytes", "字节"), ("latency", "延迟")]
for name, label in rows:
    print(f"{pad(name, 10)}| {label}")

print("display widths:", [display_width(label) for _, label in rows])

How it works

One way to read it: the functions display_width and pad, doing all the work.

Iteration happens inside for char in text — everything outside it runs once.

Caveats

  • Plan for an install step: unicodedata is a real dependency, resolved by the package manager.

Using it

Entry signature: def display_width(text: str) -> int

Output lines are prefixed (display widths:), making each step’s effect easy to spot.

display_width is the public entry point; everything else in the file exists to support it.

Key statements

def pad(text: str, width: int) -> str:
    return text + " " * (width - display_width(text))
def display_width(text: str) -> int:
    """CJK glyphs occupy two terminal cells, ASCII one."""
    return sum(
        2 if unicodedata.east_asian_width(char) in ("F", "W") else 1
        for char in text
    )

Interactive Tools for This Topic

FAQ

Which packages must be installed first?
Yes. The imports resolve to `unicodedata`, which the package manager must provide.