← 中文资源

简体中文版本

ord 与 chr 互转码点

ord 取出字符背后的码点、chr 反向还原:Python 字符串按码点迭代,同一个字符可以用不同转义写出再比较,字符级文本运算不会碰到半截符号。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

ord('A'): 65
chr(9731): ☃
roundtrip: True
chars: ['a', 'b', '☃']
code points: [97, 98, 9731]
escapes: ☃ ☃ True

实现说明

顶层就这几处状态:text。

使用要点

  • 演示输出是带标签的(ord(、chr(9731):、roundtrip:),每个操作都会留下自己的一行标注。

常见问题

依赖情况复杂吗?

一点也不复杂:零依赖,没有要锁版本或审计的东西。 文件用顶层绑定保存自己的状态:text。

代码示例

print("ord('A'):", ord("A"))
print("chr(9731):", chr(9731))
print("roundtrip:", chr(ord("A")) == "A")

# one code point per character: strings iterate by code point
text = "ab☃"
print("chars:", [ch for ch in text])
print("code points:", [ord(ch) for ch in text])

# both the \u and \N{} escapes produce the same character
print("escapes:", "\u2603", "\N{SNOWMAN}", "\u2603" == "\N{SNOWMAN}")