What's the easiest way in python to concatenate string with binary values ?
python中使用二进制值连接字符串的最简单方法是什么?
sep = 0x1
data = ["abc","def","ghi","jkl"]
Looking for result data "abc0x1def0x1ghi0x1jkl"
with the 0x1 being binary value not string "0x1".
查找结果数据“abc0x1def0x1ghi0x1jkl”,其中0x1为二进制值而非字符串“0x1”。
3 个解决方案
#1
I think
joined = '\x01'.join(data)
should do it. \x01
is the escape sequence for a byte with value 0x01.
应该这样做。 \ x01是值为0x01的字节的转义序列。
#2
The chr() function will have the effect of translating a variable into a string with the binary value you are looking for.
chr()函数将使用您要查找的二进制值将变量转换为字符串。
>>> 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.
然后可以使用join()函数将一系列字符串与二进制值作为分隔符进行连接。
>>> data = ['abc']*3
>>> data
['abc', 'abc', 'abc']
>>> sepc.join(data)
'abc\x01abc\x01abc'
#3
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:
如果需要,要删除每个字符串的最左边两位(即0b pad),值为2的slice函数[2:]工作:
>>> x=(str(bin(0b110011000)[2:]))
>>> b=(str(bin(0b11111111111)[2:]))
>>> print(x+b)
11001100011111111111
#1
I think
joined = '\x01'.join(data)
should do it. \x01
is the escape sequence for a byte with value 0x01.
应该这样做。 \ x01是值为0x01的字节的转义序列。
#2
The chr() function will have the effect of translating a variable into a string with the binary value you are looking for.
chr()函数将使用您要查找的二进制值将变量转换为字符串。
>>> 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.
然后可以使用join()函数将一系列字符串与二进制值作为分隔符进行连接。
>>> data = ['abc']*3
>>> data
['abc', 'abc', 'abc']
>>> sepc.join(data)
'abc\x01abc\x01abc'
#3
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:
如果需要,要删除每个字符串的最左边两位(即0b pad),值为2的slice函数[2:]工作:
>>> x=(str(bin(0b110011000)[2:]))
>>> b=(str(bin(0b11111111111)[2:]))
>>> print(x+b)
11001100011111111111