Python2.7打印unicode字符串仍在获取UnicodeEncodeError:“ascii”编解码器无法编码字符。。。序号不在范围内(128)

2024-10-01 17:25:04 发布

您现在位置:Python中文网/ 问答频道 /正文

一个简单的打印功能

def TODO(message):
    print(type(message))
    print(u'\n~*~ TODO ~*~ \n %s\n     ~*~\n' % message)

这样叫的

^{pr2}$

导致此错误

<type 'unicode'>                                                                                 
Traceback (most recent call last):                                                               
  File "/srv/www/proj/__init__.py", line 38, in <module>                                      
    TODO(u'api servisleri için input check decorator gerekiyor')                                 
  File "/srv/www/proj/helpers/utils.py", line 33, in TODO                                     
    print(u'\n~*~ TODO ~*~ \n %s\n     ~*~\n' % message)                                         
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 32: ordinal not in range(128)

但它在ipython控制台中工作

In [10]: TODO(u'api servisleri için input check decorator gerekiyor')
<type 'unicode'>

~*~ TODO ~*~ 
 api servisleri için input check decorator gerekiyor
     ~*~

这适用于python2.7.12,但在2.7.9中却失败了。在

我做错什么了?在

编辑:函数在flask应用程序中调用时失败,在python控制台中工作。在


Tags: inapimessageinputcheckwwwtypeunicode
3条回答

显然,print函数与print语句有点不同。在

https://docs.python.org/2.7/library/functions.html#print

All non-keyword arguments are converted to strings like 
str() does and written to the stream, separated by sep 
and followed by end. 

简单地说,编码unicode字符串就解决了这个问题

^{pr2}$

但是,不确定它为什么能与2.7.12一起工作,也许是一个语言环境问题?在

\xe7

表示小'231'的utf-8字符之一。python2.7.9可能使用ASCII编码。您可以在代表python2.7.9行为的任何版本的Python中运行下面的代码。在

import sys; 
# -*- coding: utf-8 -*-

def TODO(message):
    print(type(message))
    print(u'\n~*~ TODO ~*~ \n %s\n     ~*~\n' % message)

message = u'api servisleri için input check decorator gerekiyor'
encodedMessage = message.encode('ascii')

print(sys.stdout.encoding)
TODO(encodedMessage)

它将抛出异常

Traceback (most recent call last): File "test.py", line 9, in encodedMessage = message.encode('ascii') UnicodeEncodeError: 'ascii' codec can't encode character '\xe7' in position 16: ordinal not in range(128)

所以,这个问题和解释器的编码规则有关。你可以自己编码也可以忽略。在

希望有用

不同的终端(和gui)允许不同的编码。我手头没有最新的ipython,但它显然能够处理字符串中的非ASCII 0xe7字符('ç')。但是,您的普通控制台使用的是'ascii'编码(在异常中按名称提及),它不能显示任何大于0x7f的字节。在

如果要将非ASCII字符串打印到ASCII控制台,则必须决定如何处理它无法显示的字符。str.encode方法提供了几个选项:

str.encode([encoding[, errors]])

errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error(), see section Codec Base Classes.

下面是一个在字符串上使用这四个可选错误处理程序的示例(没有TODO添加的额外装饰):

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

from __future__ import print_function

uni = u'api servisleri için input check decorator gerekiyor'
handlers = ['ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace']
for handler in handlers:
    print(handler + ':')
    print(uni.encode('ascii', handler))
    print()

输出:

^{pr2}$

这些输出中哪一个最接近你想要的是你自己决定。在

有关更多信息,请参见Python2“Unicode HOWTO”和Ned Batchelder的“Pragmatic Unicode, or, How Do I Stop the Pain?”,也可作为36分钟video from PyCon US 2012提供。在

编辑:…或者,正如您所发现的,您的终端可以很好地显示Unicode,但是您的默认编码仍然设置为'ascii',这比它需要的限制更严格。在

相关问题 更多 >

    热门问题