← 中文资源

简体中文版本

east_asian_width 对齐 CJK 宽字符

CJK 全角字符占两个终端列宽,直接按字符数 ljust 会让表格错位;用 east_asian_width 累加显示宽度后再补空格,中英混排列才能对齐。

阅读英文原文

实现说明

真正干活的是函数 display_width、pad,其余都是接线。 在这里做循环的是 for char in text。

使用要点

  • 依赖检查:unicodedata——不是内建的,项目里必须有。
  • 跑完文件,输出里会留下标记——display widths:。
  • 值得导入的表面是 display_width;周围的辅助代码对片段是私有的。

常见问题

要先安装哪些包?

需要。导入解析到 unicodedata,由包管理器提供。

主要签名是 def display_width(text: str) -> int

核心语句

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
    )

代码示例

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])