python unichr问题

jac*_*cob 2 python unicode ubuntu

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)
Run Code Online (Sandbox Code Playgroud)

在我的桌面上(Ubuntu 9.10):

>>> print unichr(255)
ÿ
Run Code Online (Sandbox Code Playgroud)

我是python的新手,所以我不知道如何解决这个问题.有人在乎帮忙吗?谢谢.

cry*_*ryo 6

使用" print"关键字时,您将写入sys.stdout输出流.sys.stdout如果字符可以转换为ascii使用,通常只能显示Unicode字符串str(message).

打印时,您需要对操作系统的终端编码进行编码才能执行此操作.

locale模块有时可以检测输出控制台的编码:

import locale
print unichr(0xff).encode(locale.getdefaultlocale()[1], 'replace')
Run Code Online (Sandbox Code Playgroud)

但是通常最好自己指定编码,因为python经常会出错:

print unichr(0xff).encode('latin-1', 'replace')
Run Code Online (Sandbox Code Playgroud)

我认为UTF-8或latin-1经常用于许多现代Linux发行版中.

如果您知道控制台的编码,则使用" print" 时,下面的行将自动编码Unicode字符串:

import sys
import codecs
sys.stdout = codecs.getwriter(ENCODING)(sys.stdout)
Run Code Online (Sandbox Code Playgroud)

如果编码是ascii或类似的,您可能需要更改操作系统的控制台编码才能显示该字符.

另见:http://wiki.python.org/moin/PrintFails