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

标签 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

最佳答案

这一行有效:

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

关于Python 2.5 将字符串转换为二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8553310/

相关文章:

python - 通过字符串调用方法

python - 股票时间序列数据的斐波那契回撤

python - 可以在 python 2.5 中做有序字典(由于 GAE)?

python - 将邻接表变成表

python - 与 urllib2 或其他 http 库的多个(异步)连接?

python - 我可以在 Windows 中通过 ctrl-D 而不是 ctrl-Z 退出 Python 2.5 吗?

python - 正则表达式提取完整捕获组

python 使用curl上传文件

python - Jupyter 笔记本错误。没有这样的文件或目录 C :. ../HOME

python - 每个进程中的管道是否独立?