views:

427

answers:

2

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".

+9  A: 

I think

joined = '\x01'.join(data)

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

pdc
+1 Great thanks, I tried similar thing but did not think about escaping the characters to create a 'character' ...
stefanB
Works great: 8=10^A9=ABC^A10=BBB^A34=D
stefanB
+3  A: 

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'
This works as well, thanks
stefanB