我的服务器上的 unichr()
有问题。请看下面:
在我的服务器上(Ubuntu 9.04):
>>> print unichr(255)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xff' in position 0: ordinal not in range(128)
在我的桌面上(Ubuntu 9.10):
>>> print unichr(255)
ÿ
我是 python 的新手,所以我不知道如何解决这个问题。有人愿意帮忙吗?谢谢。
最佳答案
当使用“print
”关键字时,您将写入 sys.stdout
输出流。如果字符可以使用 str(message)
转换为 ascii,sys.stdout
通常只能显示 Unicode 字符串。
打印时您需要编码为操作系统的终端编码才能执行此操作。
locale
模块有时可以检测输出控制台的编码:
import locale
print unichr(0xff).encode(locale.getdefaultlocale()[1], 'replace')
但通常最好自己指定编码,因为 python 经常出错:
print unichr(0xff).encode('latin-1', 'replace')
UTF-8 或 latin-1 我认为在许多现代 linux 发行版中经常使用。
如果您知道控制台的编码,当您使用“print
”时,下面的行将自动对 Unicode 字符串进行编码:
import sys
import codecs
sys.stdout = codecs.getwriter(ENCODING)(sys.stdout)
如果编码是 ascii 或类似的东西,您可能需要更改操作系统的控制台编码才能显示该字符。
关于python unichr 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2583425/