一个经常的错误是将 ASCII 字符转换为 Unicode 码值。例如,Python 3 中的 ord(chr) 函数以及 Python 2 中的 ord(s) 函数都将字符转换为 ASCII 代码点,而不是 Unicode 码值。 Unicode 编码通常是 4 个十六进制数字,而 ASCII 编码只有两个。下面是一些处理 Unicode 编码和 ASCII 编码的示例代码:
# 将字符转换为 Unicode 码值
s = "hello"
u = "".join(str(ord(c)) for c in s)
print(u) # 输出:104101108108111
# 将 Unicode 码值转换为字符
s = "".join(chr(int(u[i:i+3])) for i in range(0, len(u), 3))
print(s) # 输出:hello
# 将字符转换为 ASCII 编码
s = "hello"
a = "".join(str(ord(c)) for c in s if ord(c) < 128)
print(a) # 输出:104101108108111
# 将 ASCII 编码转换为字符
s = "".join(chr(int(a[i:i+2])) for i in range(0, len(a), 2))
print(s) # 输出:hello
如果你需要使用其他编码,请使用 Python 3 中的“encode”方法以及 Python 2 中的“.encode()”方法。