[英]Convert a string containing hex (along with other characters) to binary in Python
I have a file containing lines of something.something(hexvalue1,hexvalue2)
我有一个包含something.something(hexvalue1,hexvalue2)
行的文件
I am trying to convert these hexvalues to binary. 我试图将这些hexvalues转换为二进制。 From what I researched I figured out I will have to search for hex values in each line and then convert them to binary. 根据我的研究,我发现我必须在每一行中搜索十六进制值,然后将它们转换为二进制。 I am not sure how to do the search in a string for hex values with other variables in it. 我不知道如何在字符串中搜索包含其他变量的十六进制值。 Note : All the lines are in the same format. 注意:所有行都采用相同的格式。
When I do : 当我做 :
for line in file:
string = line
string.split('(')
does not split at the '(' 在'('不拆分
In python, all string methods return new objects (they have to since strings are an immutable type). 在Python中,所有的字符串方法返回新对象(他们不得不因为字符串是一个不可变的类型)。 str.split
returns a list
. str.split
返回一个list
。 So to parse your string, it would be something like: 所以要解析你的字符串,它将是这样的:
for line in file:
left,right = line.split('(',1)
hexvalues = right.split(')')[0]
hex1,hex2 = hexvalues.split(',')
For those more inclined toward regular expressions: 对于那些更倾向于正则表达式的人:
import re
>>> re.findall(r'\(([^)]+)',"this.is(0xffaabb,0x112214)")
['0xffaabb,0x112214']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.