如何在 Python 中将字符串转换为二进制?

Patricia Arquette
发布: 2024-10-25 05:59:02
原创
822 人浏览过

How to Convert a String to Binary in Python?

在 Python 中将字符串转换为二进制

在 Python 中,有多种方法将字符串转换为其二进制表示形式。

使用 'ord' 函数:

此方法使用 ord() 函数获取字符串中每个字符的 Unicode 代码点。然后使用 format() 函数将代码点转换为二进制。

<code class="python">import functools

def toBinary(st):
    return ' '.join(format(ord(x), 'b') for x in st)</code>
登录后复制

使用 'bytearray':

或者,您可以使用 Python 的 bytearray 类将字符串表示为字节序列。然后可以使用 format() 函数将每个字节转换为二进制。

<code class="python">def toBinary(st):
    return ' '.join(format(x, 'b') for x in bytearray(st, 'utf-8'))</code>
登录后复制

这是一个示例:

<code class="python">st = "hello world"
print(toBinary(st))
# OR
print(' '.join(format(ord(x), 'b') for x in st))
# Output: 1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100</code>
登录后复制

以上是如何在 Python 中将字符串转换为二进制?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!