简体   繁体   English

在Python中将包含十六进制(以及其他字符)的字符串转换为二进制

[英]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.

相关问题 将十六进制字符串转换为二进制字符串,用于 python 中的串行命令 - convert string of hex characters into a binary string for serial commands in python 如何转换包含混合十六进制字符的python字节字符串? - How to convert python byte string containing a mix of hex characters? Python将包含十六进制的字符串转换为实际的十六进制 - Python convert a string containing hex to actual hex Python:如何将包含十六进制字节的字符串转换为十六进制字符串 - Python: How to convert a string containing hex bytes to a hex string 在python3中将十六进制字符串转换为字符 - Convert hex string to characters in python3 使用Python通过TCP接收的字符串中的非二进制(十六进制)字符 - Non-binary(hex) characters in string received over TCP with Python 在python中,如何将十六进制ascii字符串转换为原始内部二进制字符串? - In python, how to convert a hex ascii string to raw internal binary string? 如何将 C 二进制缓冲区转换为 Python 字符串中的十六进制表示? - How to convert a C binary buffer to it’s hex representation in Python string? 如何将 python 二进制字符串转换为十六进制? - How can I convert a python binary string to hex? Python将十六进制位转换为二进制 - python convert bit hex to binary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM