Python 2.5 convert string to binary

两盒软妹~` 提交于 2019-11-30 23:09:27

This one-line works:

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

EDIT

You can write bin() yourself

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

I think you could do it in a cleaner way like this:

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

the format function will represent the character in a 8 digits, binary representation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!