Ram
Ram

Reputation: 557

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 '('

Upvotes: 0

Views: 304

Answers (1)

mgilson
mgilson

Reputation: 310147

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']

Upvotes: 2

Related Questions