How to concatenate strings with binary values in python?
Solution 1
I think
joined = '\x01'.join(data)
should do it. \x01
is the escape sequence for a byte with value 0x01.
Solution 2
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'
Nubzor
I am a c/c++/objective-c Software Developer, mostly working on linux (Mac at home), developing software products which provide real-time connectivity to financial markets. In my free time I'm trying to keep up with what's happening in objective-c/cocoa/uikit/iOS space. In the past I have built desktop GUI in Qt, before switching to Mac. Apart from c/c++/objective-c I use python for anything else unless I find better suited tool (often plain bash scripts/make/vim/awk/sed/sqlite3 are very powerful). In the past I have worked on various modules/stacks/features that shipped as part of an mobile operating system on phones worldwide for once a major US phone manufacturer.
Updated on June 11, 2022Comments
-
Nubzor almost 2 years
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". -
Nubzor almost 15 years+1 Great thanks, I tried similar thing but did not think about escaping the characters to create a 'character' ...
-
Nubzor almost 15 yearsWorks great: 8=10^A9=ABC^A10=BBB^A34=D
-
user2284570 over 8 years@ricree : This doesn’t work with mmap.
-
user2284570 over 8 years@pdc : This doesn’t work with mmap.