为什么Python无法打印Unicode符号? [英] Why can't Python print Unicode symbols?

查看:173
本文介绍了为什么Python无法打印Unicode符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Python UnicodeDecodeError-我对编码有误解吗?

我在用Python这样打印一些unicode符号时遇到麻烦:

I am having trouble printing some unicode symbols in Python like this:

# encoding: utf-8
print u'ęėįųšįšū'

当我尝试在使用Python 2.7的VPS Ubuntu 12服务器上运行此命令时,错误:

When I try to run this on my VPS Ubuntu 12 server with Python 2.7, I get an error:


UnicodeEncodeError: ascii编解码器无法对位置0-7处的字符进行编码:序数不在范围内(128)

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-7: ordinal not in range(128)

为什么要尝试用ASCII编码?

Why does it try to encode them in ASCII?

命令正确运行

该文件已正确编码为utf-8。

The file is correctly encoded in utf-8.

推荐答案

打印 unicode 对象需要Python猜测输出编码并将Unicode代码点编码为该编码。

Printing unicode objects requires Python to guess the output encoding and encoding the Unicode codepoints to that encoding.

在您的VPS服务器上,输出编码为ASCII,这是无法检测到编码时的默认设置(例如使用管道时)。如果在终端上运行相同的代码,通常会检测到终端编码并且编码成功。

On your VPS server, the output encoding appears to be ASCII, which is the default when no encoding could be detected (such as when using a pipe). If you run the same code on a terminal, the terminal encoding is usually detected and the encoding succeeds.

解决方案是根据脚本要求显式编码。

The solution is to encode explicitly depending on your script requirements.

请务必阅读 Python Unicode HOWTO 了解Python如何进行这种检测以及为什么需要为您编码。

Please do read the Python Unicode HOWTO to understand how Python does this detection and why it needs to encode for you.

这篇关于为什么Python无法打印Unicode符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆