Python的string.format()和Unicode

时间:2012-12-02 22:33:10

标签: python unicode

我遇到了Python string.format()的问题并将Unicode字符串传递给它。这类似于this older question,但在我的情况下,测试代码会在打印时爆炸,而不是logging.info()调用。将相同的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)

尝试将output_string转换为Unicode并没有任何区别。

  

output_string = u“打印的unicode对象:{}”。format(unicode_string)

我在这里遗漏了什么吗?字符串对象的文档似乎非常清楚,这应该在我尝试使用它时起作用。

1 个答案:

答案 0 :(得分: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 ô

编辑:如果无法使用控制台的编码对unicode字符串进行编码,则print行可能不适合您。例如,在我的Windows控制台上:

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

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