python 如何在python中将字符串与二进制值连接起来?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1012457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:16:15  来源:igfitidea点击:

How to concatenate strings with binary values in python?

pythonstringbinaryconcatenation

提问by stefanB

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”的结果数据。

回答by pdc

I think

我认为

joined = '\x01'.join(data) 

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

应该这样做。\x01是值为 0x01 的字节的转义序列。

回答by ricree

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'

回答by Steven Hatzakis

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:]值为 2的 slice 函数起作用:

>>> x=(str(bin(0b110011000)[2:]))
>>> b=(str(bin(0b11111111111)[2:]))
>>> print(x+b)
11001100011111111111