简体   繁体   中英

Convert a string containing hex (along with other characters) to binary in Python

I have a file containing lines of something.something(hexvalue1,hexvalue2)

I am trying to convert these hexvalues to binary. 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). str.split returns a 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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM