Python 中的字符串到二进制

在本文中,我们将学习如何在 Python 中将字符串转换为其二进制等价物。

我们知道字符串是一个字符串序列,用引号表示。

二进制数的形式是 0 和 1,信息总是以二进制格式编码,因为这是计算机理解的。

我们将在这里使用的将字符串转换为二进制的方法是使用 join(),order(),format()和 bytearray()。

我们应该获取字符串中出现的字符的相应 ASCII 值,并将它们转换为二进制。

让我们看一下工具箱中的函数描述-

  1. join()- 它取所有的项,并将它们连接成一个实体(产生一个字符串)。
  2. order()-该方法取一个字符,并将其转换为相应的 UNICODE 值。
  3. format()- 这个方法获取一个值,并将其插入占位符所在的位置,它也用于以指定的间隔合并字符串的各个部分。
  4. bytearray()- 它返回一个字节数组。

下面的程序展示了如何做到这一点

示例-


# declaring the string
str_to_conv = "Let's learn Python"
# printing the string that will be converted
print("The string that we have taken is ",str_to_conv)
# using join() + ord() + format() to convert into binary
bin_result = ''.join(format(ord(x), '08b') for x in str_to_conv)
# printing the result
print("The string that we obtain binary conversion is ",bin_result)

输出-

The string that we have taken is  Let's learn Python
The string that we obtain binary conversion is  010011000110010101110100001001110111001100100000011011000110010101100001011100100110111000100000010100000111100101110100011010000110111101101110

解释-

让我们了解我们在上面的程序中做了什么-

  1. 首先,我们已经用值“让我们学习 Python”声明了需要转换为二进制的字符串。
  2. 下一步是显示我们创建的字符串,以便在输出的帮助下很容易理解哪一个是我们的字符串以及它的二进制等价物是什么。
  3. 然后,我们使用了 format()方法,并将其参数指定为 order()和‘08b’,这两个参数使用 for循环从字符串中获取每个字符,并将它们转换为二进制。
  4. 整个结果存储在变量 bin_result 中,最后,我们显示它的值。

在下一个示例中,我们将通过使用 bytearray()来做同样的事情。

示例- 2


# declaring the string
str_to_conv = "Let's learn Python"
# printing the string that will be converted
print("The string that we have taken is ",str_to_conv)
# using join(), format() and bytearray() to convert into binary
bin_result = ''.join(format(x,'08b') for x in bytearray(str_to_conv,'utf-8'))
# printing the result
print("The string that we obtain binary conversion is ",bin_result)

输出-

The string that we have taken is  Let's learn Python
The string that we obtain binary conversion is  010011000110010101110100001001110111001100100000011011000110010101100001011100100110111000100000010100000111100101110100011010000110111101101110  

示例-

让我们看看上面的方法有多不同-

  1. 首先,我们已经用值“让我们学习 Python”声明了需要转换为二进制的字符串。
  2. 下一步是显示我们创建的字符串,以便在输出的帮助下很容易理解哪一个是我们的字符串以及它的二进制等价物是什么。
  3. 然后我们使用了 bytearray()函数,其中使用 for循环获取字符串中的每个字符,并将其转换为二进制。
  4. 整个结果存储在变量 bin_result 中,最后,我们显示它的值。

本文链接:https://my.lmcjl.com/post/7516.html

展开阅读全文

4 评论

留下您的评论.