String转换为Unicode

String转换为Unicode

本文介绍了Python:将Unicode-Hex-String转换为Unicode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由unicode字符串和该函数构成的十六进制字符串:

  def toHex(s):
res =
for c in s:
res + =%02X%ord(c)#至少2个十六进制数字,可以更多
返回res

hex_str = toHex(u...)

这一个:

 80547CFB4EBA5DF15B585728

这是一个由6个中文符号组成的序列。

但是

  u Knödel

转换为



<$ p $ > 4B6EF664656C

我现在需要的是一个函数来转换这个回到最初的unicode。中文符号似乎有2个字节的表示形式,而第二个示例则是所有字符都有1个字节的表示形式。所以我不能只为每个1或2字节的块使用unichr()。

我已经试过了

  binascii.unhexlify(hex_str)

但这似乎是逐字节转换并返回一个字符串,而不是Unicode。我也试过

$ p $ binascii.unhexlify(hex_str).decode(...)

具有不同的格式。



预先感谢您!

解决方案

这似乎工作得很好:

  binascii.unhexlify(binascii.hexlify(uKnödel.encode 'utf-8')))。decode('utf-8')

回到原始对象。如果编码正确,您可以对中文文本执行相同的操作,但是 ord(x)已经销毁您开始的文本。您需要先对其进行编码,然后才能像字符串一样处理。


I have a hex-string made from a unicode string with that function:

def toHex(s):
    res = ""
    for c in s:
        res += "%02X" % ord(c) #at least 2 hex digits, can be more
    return res

hex_str = toHex(u"...")

This returns a string like this one:

"80547CFB4EBA5DF15B585728"

That's a sequence of 6 chinese symbols.
But

u"Knödel"

converts to

"4B6EF664656C"

What I need now is a function to convert this back to the original unicode. The chinese symbols seem to have a 2-byte representation while the second example has 1-byte representations for all characters. So I can't just use unichr() for each 1- or 2-byte block.

I've already tried

binascii.unhexlify(hex_str)

but this seems to convert byte-by-byte and returns a string, not unicode. I've also tried

binascii.unhexlify(hex_str).decode(...)

with different formats. Never got the original unicode string.

Thank you a lot in advance!

解决方案

This seems to work just fine:

binascii.unhexlify(binascii.hexlify(u"Knödel".encode('utf-8'))).decode('utf-8')

Comes back to the original object. You can do the same for the chinese text if it's encoded properly, however ord(x) already destroys the text you started from. You'll need to encode it first and only then treat like a string of bytes.

这篇关于Python:将Unicode-Hex-String转换为Unicode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 08:39