字符串转换为二进制在python [英] Convert string to binary in python

查看:774
本文介绍了字符串转换为二进制在python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种方式来获得在python字符串的二进制重新presentation。例如

I am in need of a way to get the binary representation of a string in python. e.g.

st = "hello world"
toBinary(st)

有没有的这样的一些巧妙的方式模块?

Is there a module of some neat way of doing this?

推荐答案

这样呢?

>>> st = "hello world"
>>> ' '.join(format(ord(x), 'b') for x in st)
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'

#using `bytearray`
>>> ' '.join(format(x, 'b') for x in bytearray(st))
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'

这篇关于字符串转换为二进制在python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆