【问题标题】:Converting int to Unicode char in a backwards compatible way以向后兼容的方式将 int 转换为 Unicode char
【发布时间】:2013-10-04 09:19:48
【问题描述】:

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

生成的字符串是 Unicode 字符串,可以是 Py3 中的纯字符串,也可以是 pre Py3 中的“from __future__ import unicode_literals”。

所以我们想要:

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

>>> c
'Ɣ'

【问题讨论】:

    标签: python string unicode int backwards-compatibility


    【解决方案1】:

    怎么样:

    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,也可以创建自己的函数名称。

    【讨论】:

    • 我猜它正在工作,但你正在用你得到的字符串做一些事情,这让你认为它不是。 ASCII(和 Unicode)字符 32 是一个空格,因此执行print(chr(32)) 之类的操作将打印看起来像空白行,但实际上有一个不可见的空格字符。
    猜你喜欢
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 2021-12-16
    • 2012-06-17
    • 1970-01-01
    • 2017-05-18
    • 2021-12-26
    • 2015-01-20
    相关资源
    最近更新 更多