use*_*614 88 python string binary
我需要一种方法来获取python中字符串的二进制表示.例如
st = "hello world"
toBinary(st)
Run Code Online (Sandbox Code Playgroud)
有一个简洁的方法来做这个吗?
Ash*_*ary 103
像这样的东西?
>>> st = "hello world"
>>> ' '.join(format(ord(x), 'b') for x in st)
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'
#using `bytearray`
>>> ' '.join(format(x, 'b') for x in bytearray(st))
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'
Run Code Online (Sandbox Code Playgroud)
Kas*_*mvd 43
作为一种更加pythonic的方式,您可以先将字符串转换为字节数组,然后使用以下bin
函数map
:
>>> st = "hello world"
>>> map(bin,bytearray(st))
['0b1101000', '0b1100101', '0b1101100', '0b1101100', '0b1101111', '0b100000', '0b1110111', '0b1101111', '0b1110010', '0b1101100', '0b1100100']
Run Code Online (Sandbox Code Playgroud)
或者你可以加入它:
>>> ' '.join(map(bin,bytearray(st)))
'0b1101000 0b1100101 0b1101100 0b1101100 0b1101111 0b100000 0b1110111 0b1101111 0b1110010 0b1101100 0b1100100'
Run Code Online (Sandbox Code Playgroud)
请注意,在python3中,您需要为bytearray
函数指定编码:
>>> ' '.join(map(bin,bytearray(st,'utf8')))
'0b1101000 0b1100101 0b1101100 0b1101100 0b1101111 0b100000 0b1110111 0b1101111 0b1110010 0b1101100 0b1100100'
Run Code Online (Sandbox Code Playgroud)
你也可以binascii
在python 2中使用模块:
>>> import binascii
>>> bin(int(binascii.hexlify(st),16))
'0b110100001100101011011000110110001101111001000000111011101101111011100100110110001100100'
Run Code Online (Sandbox Code Playgroud)
hexlify
返回二进制数据的十六进制表示,然后您可以通过指定16作为其基础转换为int,然后将其转换为二进制bin
.
Mar*_*ins 15
您可以使用ord()
内置函数访问字符串中字符的代码值.如果您需要将其格式化为二进制格式,则该string.format()
方法将完成此任务.
a = "test"
print(' '.join(format(ord(x), 'b') for x in a))
Run Code Online (Sandbox Code Playgroud)
(感谢Ashwini Chaudhary发布该代码段.)
虽然上面的代码在Python 3中有效,但如果您假设除了UTF-8之外的任何编码,这个问题会变得更复杂.在Python 2中,字符串是字节序列,默认情况下采用ASCII编码.在Python 3中,字符串被假定为Unicode,并且有一个单独的bytes
类型更像Python 2字符串.如果您希望采用UTF-8以外的任何编码,则需要指定编码.
在Python 3中,您可以执行以下操作:
a = "test"
a_bytes = bytes(a, "ascii")
print(' '.join(["{0:b}".format(x) for x in a_bytes]))
Run Code Online (Sandbox Code Playgroud)
对于简单的字母数字字符串,UTF-8和ascii编码之间的差异并不明显,但如果您处理的文本包含不在ascii字符集中的字符,则会变得很重要.
在 Python 3.6 及更高版本中,您可以使用f-string来格式化结果。
str = "hello world"
print(" ".join(f"{ord(i):08b}" for i in str))
01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01101100 01100100
Run Code Online (Sandbox Code Playgroud)
冒号的左侧 ord(i) 是实际对象,其值将被格式化并插入到输出中。使用 ord() 为您提供单个 str 字符的 base-10 代码点。
冒号的右侧是格式说明符。08 表示宽度为 8,填充为 0,b 用作符号以输出基数为 2(二进制)的结果数。