4

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

1
  • No binary values there. 0x1 is hexadecimal; 0b1 would be binary. Commented Nov 2, 2017 at 2:37

3 Answers 3

11

I think

joined = '\x01'.join(data) 

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

Sign up to request clarification or add additional context in comments.

3 Comments

+1 Great thanks, I tried similar thing but did not think about escaping the characters to create a 'character' ...
Works great: 8=10^A9=ABC^A10=BBB^A34=D
@pdc : This doesn’t work with mmap.
4

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'

1 Comment

@ricree : This doesn’t work with mmap.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.