Convert from hex character to Unicode character in python

耗尽温柔 提交于 2019-12-07 05:43:44

问题


The hex string '\xd3' can also be represented as: Ó.

The easiest way I've found to get the character representation of the hex string to the console is:

print unichr(ord('\xd3'))

Or in English, convert the hex string to a number, then convert that number to a unicode code point, then finally output that to the screen. This seems like an extra step. Is there an easier way?


回答1:


print u'\xd3'

Is all you have to do. You just need to somehow tell Python it's a unicode literal; the leading u does that. It will even work for multiple characters.

If you aren't talking about a literal, but a variable:

codepoints = '\xd3\xd3'
print codepoints.decode("latin-1")

Edit: Specifying a specific encoding when printing will not work if it's incompatible with your terminal encoding, so just let print do encode(sys.stdout.encoding) automatically. Thanks @ThomasK.



来源:https://stackoverflow.com/questions/6999737/convert-from-hex-character-to-unicode-character-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!