简体   繁体   English

在python中从十六进制字符转换为Unicode字符

[英]Convert from hex character to Unicode character in python

The hex string '\\xd3' can also be represented as: Ó .十六进制字符串'\\xd3'也可以表示为: Ó

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.或者在英语中,将十六进制字符串转换为数字,然后将该数字转换为 unicode 代码点,最后将其输出到屏幕。 This seems like an extra step.这似乎是一个额外的步骤。 Is there an easier way?有更容易的方法吗?

print u'\xd3'

Is all you have to do.这就是你所要做的。 You just need to somehow tell Python it's a unicode literal;你只需要以某种方式告诉 Python 它是一个 unicode 文字; the leading u does that.领导u这样做。 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 print ing will not work if it's incompatible with your terminal encoding, so just let print do encode(sys.stdout.encoding) automatically.编辑:如果与您的终端编码不兼容,则在print时指定特定编码将不起作用,因此只需让print自动执行encode(sys.stdout.encoding) Thanks @ThomasK.谢谢@ThomasK。

if data is something like this "\\xe0\\xa4\\xb9\\xe0\\xa5\\x88\\xe0\\xa4\\xb2\\xe0\\xa5\\x8b \\xe0\\xa4\\x95\\xe0\\xa4\\xb2"如果数据是这样的“\\xe0\\xa4\\xb9\\xe0\\xa5\\x88\\xe0\\xa4\\xb2\\xe0\\xa5\\x8b\\xe0\\xa4\\x95\\xe0\\xa4\\xb2”

sys.stdout.buffer.write(data) 

would print会打印

हैलो कल

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM