我在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)
我失去了一些东西在这里?字符串对象的文档似乎很清楚,这应该工作,因为我试图使用它。
使用上面的代码,但预先在'u打印的unicode对象'工作于我(Python 2.6.5和2.7)。当你这样做的时候,你得到的错误与上面列出的一样吗? – RocketDonkey
等等......你正在编码一个应该表示已经编码的unicode流的unicode字节流? “\ xc3 \ xb4''上面应该打印什么字符:'ô'或'Ã''? –
它应该是ô。编码示例几乎是从引用的关于日志记录模块的旧帖子逐字拷贝的。 – mpounsett