如何将字符串转换为二进制? [英] How to convert string to binary?

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

问题描述

我需要一种方法来获取python中字符串的二进制表示形式.例如

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, 'utf-8'))
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'

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

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