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

5 投票
2 回答
10673 浏览
提问于 2025-04-17 08:35

我知道在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 个回答

1

我觉得你可以用更简单的方法来实现,比如这样:

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

这个格式化函数会把字符转换成8位的二进制表示。

7

这一行代码可以正常运行:

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

撰写回答