2012-12-02 57 views
16

我在Python的string.format()上遇到了问题,并将Unicode字符串传递给它。这与this older question类似,只是在我的情况下,测试代码在打印时爆炸,而不是在logging.info()呼叫上爆炸。将相同的Unicode字符串对象传递给日志处理程序可以正常工作。Python的string.format()和Unicode

这与旧的%格式以及string.format()的格式不符。只是为了确保它是字符串对象是问题,而不是打印与我的终端严重交互,我试图在打印前将格式化的字符串分配给变量。

def unicode_test(): 
    byte_string = '\xc3\xb4' 
    unicode_string = unicode(byte_string, "utf-8") 
    print "unicode object type: {}".format(type(unicode_string)) 
    output_string = "printed unicode object: {}".format(unicode_string) 
    print output_string 

if __name__ == '__main__': 
    unicode_test() 

字符串对象似乎认为它正在获取ASCII。

% python -V 
Python 2.7.2 

% python ./unicodetest.py 
unicode object type: <type 'unicode'> 
Traceback (most recent call last): 
    File "./unicodetest.py", line 10, in <module> 
    unicode_test() 
    File "./unicodetest.py", line 6, in unicode_test 
    output_string = "printed unicode object: {}".format(unicode_string) 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf4' in position 0: ordinal not in range(128) 

试图将Unicode转换为output_string作为没有任何区别。

output_string = U “印刷的unicode对象:{}”。格式(UNICODE_STRING)

我失去了一些东西在这里?字符串对象的文档似乎很清楚,这应该工作,因为我试图使用它。

+0

使用上面的代码,但预先在'u打印的unicode对象'工作于我(Python 2.6.5和2.7)。当你这样做的时候,你得到的错误与上面列出的一样吗? – RocketDonkey

+0

等等......你正在编码一个应该表示已经编码的unicode流的unicode字节流? “\ xc3 \ xb4''上面应该打印什么字符:'ô'或'Ã''? –

+0

它应该是ô。编码示例几乎是从引用的关于日志记录模块的旧帖子逐字拷贝的。 – mpounsett

回答

22

不应该这样做(你可以引用文档的说明的部分?),但它应该工作,如果格式化模式是unicode(或与旧的格式'促进'模式unicode而不是试图“降级”论据)。

>>> x = "\xc3\xb4".decode('utf-8') 
>>> x 
u'\xf4' 
>>> x + 'a' 
u'\xf4a' 
>>> 'a' + x 
u'a\xf4' 
>>> 'a %s' % x 
u'a \xf4' 
>>> 'a {}'.format(x) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec 
    can't encode character u'\xf4' in position 0: ordinal not in range(128) 
>>> u'a {}'.format(x) 
u'a \xf4' 
>>> print u"Foo bar {}".format(x) 
Foo bar ô 

编辑:print行可能不适合你,如果Unicode字符串不能使用控制台的编码进行编码。例如,在我的Windows控制台上:

>>> import sys 
>>> sys.stdout.encoding 
'cp852' 
>>> u'\xf4'.encode('cp852') 
'\x93' 

在UNIX控制台上,这可能与您的区域设置有关。如果你重定向输出,它也会失败(就像在shell中使用|一样)。大多数问题已在Python 3中修复。

+0

@mpounsett:就像你在我发布的控制台会话中看到的那样,'u'Whatever {}'.format(u'\ xf4')'工程,所以你可能想重新检查你的代码。错误是否完全一样?它是发生在同一行还是更像:http://ideone.com/Z3y5Kg? – lqc

+0

Hrm ..我以为错误是完全一样的,但是在重新检查时,我发现它实际上是迁移到了打印语句。 – mpounsett