python - 字符串(到二进制)到 python 中的 int?

标签 python

我想在 python 中从一个字符串生成一个 int。我想像这样先将字符串翻译成二进制:

st = 'string'
binSt = ' '.join(format(ord(x), '08b') for x in st)

返回这个:

01110011 01110100 01110010 01101001 01101110 01100111

然后我想将二进制(以 8 为一组)转换为应该返回的整数:

115 116 114 105 110 103

我该怎么做? python 中是否有特殊功能?

最佳答案

您可以使用 int()功能:

result = ''
st = 'string'
binSt = ' '.join(format(ord(x), '08b') for x in st)
binSt_split = binSt.split()
for split in binSt_split:
    result = result + str(int(split,2) + ' '
print result

关于python - 字符串(到二进制)到 python 中的 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36870475/

相关文章:

python - 是否有任何功能可以定位 PySpark 数据框列中的所有事件?

python - 如果切片没有创建列表的副本,list() 也没有,我如何才能获得列表的真实副本?

使用 Eclipse + PyDev 在 Linux 中进行 Python Gtk+ 开发, Unresolved 导入 : Gtk

python - 使用 Python 展平和解压字典

python - 检查 Python 元组中元素之间的相似性

Python:将字典的项目除以取决于第一个键的值

python - python 中的 `and` 和 `or` 是否存在 Dunder 方法(魔术方法)?

python - 用Python中的字典值替换正则表达式匹配组

jquery - 为什么 Django 在使用 ajax 保存记录后将我重定向到我的 api View ?

python - sklearn.linear_model.LogisticRegression 中回归的工作原理