将 unicode 字符串转换为十六进制表示 [英] Converting unicode string to hexadecimal representation
问题描述
我想将 unicode 字符串转换为其十六进制表示.例如,u'\u041a\u0418\u0421\u0410'
应该转换为"\xD0\x9A\xD0\x98\xD0\xA1\xD0\x90"
.我尝试了下面的代码(python 2.7):
unicode_username.encode("utf-8").encode("hex")
但是,我得到一个字符串:
'd09ad098d0a1d090'
有什么建议可以让我得到 \xD0\x9A\xD0\x98\xD0\xA1\xD0\x90
?
当你执行 string.encode('utf-8')
时,它会变成十六进制表示法.
但是如果你打印它,你会得到原始的unicode字符串.
如果你想要十六进制表示法,你可以用 repr()
函数得到它:
I want to convert unicode string to its hexadecimal representation.
For example, u'\u041a\u0418\u0421\u0410'
should be converted to "\xD0\x9A\xD0\x98\xD0\xA1\xD0\x90"
. I tried the code below (python 2.7):
unicode_username.encode("utf-8").encode("hex")
However, I get a string:
'd09ad098d0a1d090'
Any suggestions how I can get \xD0\x9A\xD0\x98\xD0\xA1\xD0\x90
?
When you do string.encode('utf-8')
, it changes to hex notation.
But if you print it, you will get original unicode string.
If you want the hex notation you can get it like this with repr()
function:
>>> print u'\u041a\u0418\u0421\u0410'.encode('utf-8')
КИСА
>>> print repr(u'\u041a\u0418\u0421\u0410'.encode('utf-8'))
'\xd0\x9a\xd0\x98\xd0\xa1\xd0\x90'
这篇关于将 unicode 字符串转换为十六进制表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!