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

时间:2011-12-18 17:06:57

标签: python python-2.5

我知道这在python 2.6中很容易实现。但是在Python 2.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并把它变成

  

00100010010101000110100001101001011100110010000001101001011100110010000001101101011110010010000001110011011101000111001001101001011011100110011100100010

2 个答案:

答案 0 :(得分:6)

这个单行有效:

>>> ''.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'

答案 1 :(得分:0)

我认为你可以用这样一个更清洁的方式做到这一点:

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

格式化函数将以8位二进制表示形式表示字符。