Question

What's the easiest way in python to concatenate string with binary values ?

sep = 0x1
data = ["abc","def","ghi","jkl"]

Looking for result data "abc0x1def0x1ghi0x1jkl" with the 0x1 being binary value not string "0x1".

Was it helpful?

Solution

I think

joined = '\x01'.join(data) 

should do it. \x01 is the escape sequence for a byte with value 0x01.

OTHER TIPS

The chr() function will have the effect of translating a variable into a string with the binary value you are looking for.

>>> sep = 0x1
>>> sepc = chr(sep)
>>> sepc
'\x01'

The join() function can then be used to concat a series of strings with your binary value as a separator.

>>> data = ['abc']*3
>>> data
['abc', 'abc', 'abc']
>>> sepc.join(data)
'abc\x01abc\x01abc'

I know this isn't the best method, but another way that could be useful in different context for the same question is:

>>> x=(str(bin(0b110011000)))
>>> b=(str(bin(0b11111111111)))
>>> print(x+b)
0b1100110000b11111111111

And if needed, to remove the left-most two bits of each string (i.e. 0b pad) the slice function [2:] with a value of 2 works:

>>> x=(str(bin(0b110011000)[2:]))
>>> b=(str(bin(0b11111111111)[2:]))
>>> print(x+b)
11001100011111111111
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top