Python的string.format()和Unicode

mpo*_*ett 16 python unicode

我遇到了Python的问题string.format()并将Unicode字符串传递给它.这与旧的问题类似,只是在我的情况下,测试代码在打印时爆炸,而不是在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()
Run Code Online (Sandbox Code Playgroud)

字符串对象似乎假设它正在获得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)
Run Code Online (Sandbox Code Playgroud)

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

output_string = u"打印的unicode对象:{}".format(unicode_string)

我在这里错过了什么吗?字符串对象的文档似乎很清楚,这应该可以正常,因为我正在尝试使用它.

lqc*_*lqc 23

不,这不应该工作(你能引用文档的部分说明吗?),但是如果格式化模式是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 ô
Run Code Online (Sandbox Code Playgroud)

编辑:print如果无法使用控制台的编码对unicode字符串进行编码,则该行可能无法正常工作.例如,在我的Windows控制台上:

>>> import sys
>>> sys.stdout.encoding
'cp852'
>>> u'\xf4'.encode('cp852')
'\x93'
Run Code Online (Sandbox Code Playgroud)

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