迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

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

作者:迹忆客 最近更新:2023/12/17 浏览次数:

当字符串转换为二进制时,它将生成代表原始字符的二进制值列表。每个字符都必须迭代并转换为二进制。

本文将讨论一些在 Python 中将字符串转换为其二进制表示的方法。


在 Python 中使用 format() 函数将字符串转换为二进制表示

我们使用 ord() 函数将字符串的 Unicode 点转换为相应的整数。format() 函数使用 b 二进制格式将整数转换为以 2 为底的数字。

完整的示例代码如下。

string = "Python"
binary_converted = " ".join(format(ord(c), "b") for c in string)
print("The Binary Representation is:", binary_converted)

输出:

The Binary Represntation is: 1010000 1111001 1110100 1101000 1101111 1101110

在 Python 中使用 bytearray 方法将字符串转换为二进制表示

字节数组是一组字节,可以存储二进制数据列表。除了可以显式遍历字符串之外,我们还可以遍历字节序列。可以不使用 ord() 函数,而是使用 bytearray() 函数来实现。

完整的示例代码如下。

string = "Python"
binary_converted = " ".join(format(c, "b") for c in bytearray(string, "utf-8"))
print("The Binary Represntation is:", binary_converted)

输出:

The Binary Representation is: 1010000 1111001 1110100 1101000 1101111 1101110

在 Python 中使用 map() 函数将一个字符串转换为二进制表示

我们也可以使用 map() 函数来代替 format() 函数。map() 使用 bytearray() 函数将字符串转换为字节数组,然后使用 bin 将字节数组转换为二进制表示。

完整的示例代码如下。

string = "Python"
binary_converted = " ".join(map(bin, bytearray(string, "utf-8")))
print("The Binary Represntation is:", binary_converted)

在 Python 3 中,我们必须定义一个类似于 utf-8 的编码方案。否则,将引发错误。

输出:

The Binary Represntation is: 0b1010000 0b1111001 0b1110100 0b1101000 0b1101111 0b1101110

在 Python 中使用 ASCII 方法将字符串转换为二进制表示

在 Python 3 中,utf-8 是默认的编码方案。但是这种方法将使用 ASCII 编码方案,而不是 utf-8。对于基本的字母数字字符串,UTF-8ASCII 编码之间的差异并不明显。但是,如果我们处理的文本包含的字符不属于 ASCII 字符集,则它们将变得很重要。

完整的示例代码如下:

st = "Python"
a_bytes = bytes(st, "ascii")
binary_converted = " ".join(["{0:b}".format(x) for x in a_bytes])
print("The Binary Represntation is:", binary_converted)

输出:

The Binary Representation is: 1010000 1111001 1110100 1101000 1101111 1101110

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便