【问题标题】:How to print Unicode in Python 2 when LANG=C当 LANG=C 时如何在 Python 2 中打印 Unicode
【发布时间】:2012-07-12 18:21:27
【问题描述】:

我知道,这是一个非常愚蠢的问题。当然通常 LANG=C 表示 ASCII 终端 无法显示 Unicode 字符。但我仍然想打印出 UTF-8 字节。我使用 Python 2(实际上是 2.6.5)

print '\xc3\xa4', u'\xe4'

这会在 Unicode 终端上打印 'ä ä',但第二个字符串在使用 LANG=C 执行时会导致错误。我不希望 Python 变得聪明,而只是将 u'\xe4' 转换为 UTF-8,所以它只是 '\xc3\xa4' 在内存中。

我尝试了所有可以想象的 decode()、encode() 和 unicode() 组合,但似乎我错过了正确的组合。

我真正想要的是通过 vi 的 system() 函数读取 Unicode 字符,比如

:echo system('python foo.py')

【问题讨论】:

    标签: python unicode


    【解决方案1】:

    要将unicode 编码为utf-8,请在其上调用.encode('utf-8')。:

    >>> u'\xe4'.encode('utf-8')
    '\xc3\xa4'
    

    【讨论】:

    • 嗯,可以在 LANG=C python foo.py 中使用,我可以发誓我试过了。
    猜你喜欢
    • 1970-01-01
    • 2021-12-26
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多