Skip to main content
 首页 » 编程设计

python之以向后兼容的方式将 int 转换为 Unicode char

2025年05月04日6del

有没有一种方法可以将表示 Unicode 代码点的 int 转换为 Python 中的 Unicode 字符(字符串),其中相同的转换代码可以在 Python3+ 和 Python 2.7 中运行。

结果字符串是一个 Unicode 字符串,可以是 Py3 中的纯字符串或在 Py3 之前使用“from __future__ import unicode_literals”。

所以我们想要:

i = 404 
c = chr_or_unichr (i) # this code is identical for different Python versions 
 
>>> c 
'Ɣ' 

请您参考如下方法:

怎么样:

try: 
    chr = unichr  # Python 2 
except NameError: 
    pass          # Python 3 
 
i = 404 
c = chr(i) # c is now 'Ɣ' regardless of Python version 

如果您不想覆盖 Python 2 的 chr,您也可以创建自己的函数名。