Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.5将字符串转换为二进制_Python_Python 2.5 - Fatal编程技术网

Python 2.5将字符串转换为二进制

Python 2.5将字符串转换为二进制,python,python-2.5,Python,Python 2.5,我知道这在Python2.6中很容易实现。但是在Python2.5中,最简单的方法是什么呢 x = "This is my string" b = to_bytes(x) # I could do this easily in 2.7 using bin/ord 3+ could use b"my string" print b 有什么建议吗?我想把x变成 00100010010010101010001101000010100101111001000001010010111001000000

我知道这在Python2.6中很容易实现。但是在Python2.5中,最简单的方法是什么呢

x = "This is my string"
b = to_bytes(x)  # I could do this easily in 2.7 using bin/ord 3+ could use b"my string"
print b
有什么建议吗?我想把x变成

00100010010010101010001101000010100101111001000001010010111001000000111001000001011010111100100100000011100110111010001110010010010010011011100110011100100010

这一行的作用是:

>>> ''.join(['%08d'%int(bin(ord(i))[2:]) for i in 'This is my string'])
'0101010001101000011010010111001100100000011010010111001100100000011011010111100100100000011100110111010001110010011010010110111001100111'
编辑

您可以自己编写
bin()

def bin(x):
    if x==0:
        return '0'
    else:
        return (bin(x/2)+str(x%2)).lstrip('0') or '0'

我想你可以用一种更干净的方式来做:

>>>''.join(format(ord(c), '08b') for c in 'This is my string')
'0101010001101000011010010111001100100000011010010111001100100000011011010111100100100000011100110111010001110010011010010110111001100111'

format函数将用8位二进制表示字符。

您的“xml字符串”真的是str()而不是unicode()对象吗?它是str()。格式几乎与上面一样,我可以将其设置为unicode。实际上,字节文字表示法是2.6+。请尝试
echo-n“这是我的字符串”| xxd-b
相关:@Nix您可以自己编写
bin()