Python';s string.format()和Unicode

Python';s string.format()和Unicode,python,unicode,Python,Unicode,Python的string.format()和传递Unicode字符串时出现问题。这与类似,只是在我的例子中,测试代码在打印时爆炸,而不是在logging.info()调用中爆炸。将相同的Unicode字符串对象传递给日志处理程序可以正常工作 对于较旧的%格式以及string.format()。为了确保问题出在字符串对象上,并且打印与终端的交互不好,我尝试在打印之前将格式化字符串分配给变量 def unicode_test(): byte_string = '\xc3\xb4'

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()
string对象似乎假定它正在获取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)
%python-V
Python 2.7.2
%python./unicodetest.py
unicode对象类型:
回溯(最近一次呼叫最后一次):
文件“/unicodetest.py”,第10行,在
unicode_测试()
unicode\u测试中的第6行文件“/unicodetest.py”
输出字符串=“打印的unicode对象:{}”。格式(unicode字符串)
UnicodeEncodeError:“ascii”编解码器无法对位置0中的字符u'\xf4'进行编码:序号不在范围内(128)
尝试将
output\u string
转换为Unicode没有任何区别

输出字符串=u“打印的unicode对象:{}”。格式(unicode字符串)

我是不是遗漏了什么?字符串对象的文档似乎非常清楚,在我尝试使用它时,它应该可以工作。

不,这不应该工作(您可以引用文档中这样说的部分吗?),但如果格式化模式是unicode,它应该可以工作(或者使用旧格式将模式“升级”为unicode,而不是尝试“降级”参数)


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

如上所述使用代码,但使用
u
预写
打印的unicode对象对我来说是可行的(Python 2.6.5和2.7)。执行此操作时遇到的错误是否与上面列出的相同?等等…您正在编码一个unicode字节流,该字节流应该表示已编码的unicode流?上面应该为
'\xc3\xb4'
打印什么字符:
ô
Ã'
?应该是ô。编码示例复制得很好从引用的关于日志模块的旧帖子中逐字记录。是的,当我在字符串前面加上
u
时,我得到了相同的错误。您的默认编码是什么?请尝试:
import sys;print sys.getdefaultencoding()
@mpouncet:正如您在我发布的控制台会话中看到的那样,
u'Whatever{}'。格式(u'\xf4')
正常工作,因此您可能需要重新检查代码。错误是否完全相同?是发生在同一行还是更像:?Hrm..我原以为错误完全相同,但在重新检查时,我看到它实际上迁移到了打印语句。
>>> 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 ô
>>> import sys
>>> sys.stdout.encoding
'cp852'
>>> u'\xf4'.encode('cp852')
'\x93'