在Python中将十六进制字符串表示转换为实际字节 [英] Converting a hex-string representation to actual bytes in Python

查看:1274
本文介绍了在Python中将十六进制字符串表示转换为实际字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要加载这个文本文件的第三列作为十六进制字符串



http://www.netmite.com/android/mydroid/1.6/external/skia/emoji/gmojiraw.txt

 >>> (''\'')[0] .split xBE\\\x80\\x80'

如何打开文件以便我可以以十六进制字符串的形式获得第三列:

 '\xF3\xBE\x80\x80'

我也试过二进制模式和十六进制模式,但没有成功。



  1. 删除 \x

  2. 对结果字符串使用.decode('hex')

代码:

 >>> '\\xF3\\\xBE\\x80\\x80'.replace('\\x','').decode('hex')
'\ xf3\xbe\x80\x80'

注意对反斜杠的适当解释。当字符串表示形式为'\xf3'时,这意味着它是一个字节值为0xF3的单字节字符串。当它是'\\xf3'时,它是您的输入,它表示一个由4个字符组成的字符串: \ x f 3


i need to load the third column of this text file as a hex string

http://www.netmite.com/android/mydroid/1.6/external/skia/emoji/gmojiraw.txt

>>> open('gmojiraw.txt').read().split('\n')[0].split('\t')[2]
'\\xF3\\xBE\\x80\\x80'

how do i open the file so that i can get the third column as hex string:

'\xF3\xBE\x80\x80'

i also tried binary mode and hex mode, with no success.

解决方案

You can:

  1. Remove the \x-es
  2. Use .decode('hex') on the resulting string

Code:

>>> '\\xF3\\xBE\\x80\\x80'.replace('\\x', '').decode('hex')
'\xf3\xbe\x80\x80'

Note the appropriate interpretation of backslashes. When the string representation is '\xf3' it means it's a single-byte string with the byte value 0xF3. When it's '\\xf3', which is your input, it means a string consisting of 4 characters: \, x, f and 3

这篇关于在Python中将十六进制字符串表示转换为实际字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆